2011-02-03 3 views
1

У меня есть эта функция, которая медленно удаления дубликатов в VB6удалить дублирует быстрее vb6

Function FilterDuplicates(Arr As Variant) As Long 
    Dim col  As Collection, index As Long, dups As Long 
    Set col = New Collection 

    On Error Resume Next 

    For index = LBound(Arr) To UBound(Arr) 
     ' build the key using the array element 
     ' an error occurs if the key already exists 
     col.Add 0, CStr(Arr(index)) 
     If Err Then 
      ' we've found a duplicate 
      Arr(index) = Empty 
      dups = dups + 1 
      Err.Clear 
     ElseIf dups Then 
      ' if we've found one or more duplicates so far 
      ' we need to move elements towards lower indices 
      Arr(index - dups) = Arr(index) 
      Arr(index) = Empty 
     End If 
    Next 

    ' return the number of duplicates 
    FilterDuplicates = dups 

End Function 

мне нужно оптимизировать эту функцию, чтобы работать быстрее, пожалуйста, помогите

+0

Я обновил свой ответ, чтобы добавить конечный бит. Я должен спросить, было ли это домашнее задание? –

+0

Нет, это не домашнее задание, но почему вы спросили об этом? – Smith

ответ

1
Function FilterDuplicates(Arr As Variant) As Long 
    Dim col  As Dictionary, index As Long, dups As Long 
    Set col = New Dictionary 

    On Error Resume Next 

    For index = LBound(Arr) To UBound(Arr) 
     ' build the key using the array element 
     ' an error occurs if the key already exists 
     If col.Exists(Arr(index)) Then 
      ' we've found a duplicate 
      dups = dups + 1 
     Else 
      Call col.Add(Arr(index), vbNullstring) 
     End If 
    Next 

    Dim newArr(1 to col.Keys.Count) As Variant 
    Dim newIndex As Long 
    For index = LBound(Arr) To UBound(Arr) 
     If col(Arr(index)) = vbNullstring Then 
      newIndex = newIndex + 1 
      col(Arr(index)) = "Used" 
      newArr(newIndex) = Arr(index) 
     End If 
    Next index 
    Arr = newArr 

    ' return the number of duplicates 
    FilterDuplicates = dups 

End Function 
+0

функция не завершена, как я могу ее использовать? – Smith

+2

Две вещи. Во-первых, вы должны добавить ссылку на «Microsoft Scripting Runtime» в свой проект, используя диалог «Проект/Ссылки», чтобы вы могли использовать словарь. Во-вторых, на строке 'If col.Exists ...' отсутствует 'Then'. Поскольку он неполный, все, что ему не хватает, это перестроение массива, исключая те элементы, которые существуют в 'col', как только команда For/Next завершена. Вы можете справиться с этим, я бы подумал ...? Подсказка: другой цикл For/Next? – JeffK

+0

вместо использования коллекции, не могу ли я просто использовать обычный массив? – Smith

Смежные вопросы