删除字符串数组中的所有连续重复项

时间:2016-05-08 19:00:32

标签: c++ arrays string duplicates

我正在尝试删除c ++字符串数组中的所有重复项。我有代码,但它导致我的程序什么都不做。

int removeDups(string a[], int n)
{

    if (n < 0)
    {
        return -1;
    }

    int k = 0;
    int retained = 0;

    while (k<n)
    {
        if (a[k] == a[k + 1])
        {
            for (int j = k+1; j < (n-k); j++)
            {
                a[j] = a[j + 1];
            }
        }

        else 
        {
            retained++;
            k++;
        }

    }

    return retained;

}

该函数应该考虑数组中的前n个项,删除任何连续的重复项,并返回保留的唯一项的数量(在数组的前n项中)。我不能使用矢量或任何花哨的东西。

4 个答案:

答案 0 :(得分:1)

C ++方式:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

void distinct(vector<string>& vec)
{
    // First sort words alphabetically so we can find the duplicates.
    sort(begin(vec), end(vec)); 

    // Unique algorithm rearranges the input range to "mark for deletion"
    // adjacent duplicated entries and return iterator that 
    // denotes the end of the range of the unique values
    auto end_unique = unique(begin(vec), end(vec));
    // then remove the nonunique elements
    vec.erase(end_unique, end(vec));
}

int main(int argc, const char * argv[]) {

    vector<string> words {"car", "apple", "box", "car", "apple", "foo"};
    // remove dups
    distinct(words);

    for (const auto& word : words) {
        cout << word << ' ';
    }

    return 0;
}

结果:苹果盒车foo

答案 1 :(得分:0)

a不是数组,而是指针。 sizeof(a)将是4或8,而不是数组中的字节数(无论如何都是错误的值,你需要除以数组元素的大小)。

您需要使用数组中的元素数量 - 您可以方便地使用它们:n

一旦你拖沓,你也应该减少n。最后,最好使用std :: move,以便移动字符串而不是复制字符串。

答案 2 :(得分:0)

这是一种方法:

/// Removes any consecutive duplicates in the string array.
/// Returns the number of elements retained (numOriginal - numRemoved)
int removeDups(string arr[], int n){
    int numDeleted = 0; // keep track of how many duplicates we've deleted

    // search for duplicates
    int i = 0;
    while (i < n - 1){
        // check if all remaining elements are equal
        bool restAreEqual = true;
        for (int j = i, m = n - 1; j < m; j++){
            if (arr[j] != arr[j + 1]){
                restAreEqual = false;
            }
        }

        // if the next element is equal to this one (but not all the rest are equal)
        if (arr[i] == arr[i+1] && !restAreEqual){
            numDeleted++; // delete it
            // shift all subsequent items one to the left
            for (int j = i + 1, m = n - 1; j < m; j++){
                arr[j] = arr[j + 1];
            }
            continue;
        }

        i++;
    }

    return n - numDeleted;
}

答案 3 :(得分:0)

我用“”替换了重复的连续字符串。不确定这是否是你删除它们的意思。

int nonduplicates(string str[], int num){
int retained = 0;
for (int i = 0; i < num; i++){
    if ( str[i] == str[i+1]){
        str[i] = " ";
        str[i+1] = " ";
        i++;
    }
    else
        retained++;
}
return retained;

}