c++ - 检查大型字符串 vector 中的重复项

标签 c++

我正在尝试查找重复的字符串实例,其中我有一个包含约 250 万个字符串的 vector 。~

目前我使用类似的东西:

std::vector<string> concatVec; // Holds all of the concatenated strings containing columns C,D,E,J and U.
std::vector<string> dupecheckVec; // Holds all of the unique instances of concatenated columns
std::vector<unsigned int> linenoVec; // Holds the line numbers of the unique instances only

// Copy first element across, it cannot be a duplicate yet
dupecheckVec.push_back(concatVec[0]);
linenoVec.push_back(0);

// Copy across and do the dupecheck
for (unsigned int i = 1; i < concatVec.size(); i++)
{
    bool exists = false;

    for (unsigned int x = 0; x < dupecheckVec.size(); x++)
    {
        if (concatVec[i] == dupecheckVec[x])
        {
            exists = true;
        }
    }

    if (exists == false)
    {
        dupecheckVec.push_back(concatVec[i]);
        linenoVec.push_back(i);
    }
    else
    {
        exists = false;
    }
}

这对于小文件来说很好,但由于嵌套的 for 循环和 dupecheckVec 中包含的字符串数量增加,随着文件大小的增长,显然最终会花费非常长的时间。

在大文件中执行此操作的不那么可怕的方法是什么?

最佳答案

如果您不介意重新排序 vector ,那么这应该在 O(n*log(n)) 时间内完成:

std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());

为了保留顺序,您可以改为使用 (line-number, string*) 对 vector :按字符串排序,使用比较字符串内容的比较器进行 uniquify,最后按行号排序,如下所示:

struct pair {int line, std::string const * string};

struct OrderByLine {
    bool operator()(pair const & x, pair const & y) {
        return x.line < y.line;
    }
};

struct OrderByString {
    bool operator()(pair const & x, pair const & y) {
        return *x.string < *y.string;
    }
};

struct StringEquals {
    bool operator()(pair const & x, pair const & y) {
        return *x.string == *y.string;
    }
};

std::sort(vector.begin(), vector.end(), OrderByString());
vector.erase(std::unique(vector.begin(), vector.end(), StringEquals()), vector.end());
std::sort(vector.begin(), vector.end(), OrderByLine());

关于c++ - 检查大型字符串 vector 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5487197/

相关文章:

c++ - 将 Boost Asio 与 ZeroMQ、错误的文件描述符集成?

c++ - Boost 的 Sublime Text 2 问题

c++ - 将类的 move 成员作为const引用参数传递

C++ 用常量值填充数组,循环和改变值

C++ 对析构函数的 undefined reference

c++ - C++ 中 ODE 类的设计模式

C++ OPENSSL 库 HMAC 函数返回值每次运行时都不一样?

c++ - 为什么我的 do-while 循环不继续循环?

c++ - powerset 中的组合或子集的 next_permutation

c++ - 通过 visual studio 2010 项目模板设置 cocos2d-x 应用程序