c – 检查大型字符串向量中的重复项

前端之家收集整理的这篇文章主要介绍了c – 检查大型字符串向量中的重复项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图找到重复的字符串实例,其中我有一个~250万字符串的向量.~

目前我使用的东西如下:

  1. std::vector<string> concatVec; // Holds all of the concatenated strings containing columns C,D,E,J and U.
  2. std::vector<string> dupecheckVec; // Holds all of the unique instances of concatenated columns
  3. std::vector<unsigned int> linenoVec; // Holds the line numbers of the unique instances only
  4.  
  5. // Copy first element across,it cannot be a duplicate yet
  6. dupecheckVec.push_back(concatVec[0]);
  7. linenoVec.push_back(0);
  8.  
  9. // Copy across and do the dupecheck
  10. for (unsigned int i = 1; i < concatVec.size(); i++)
  11. {
  12. bool exists = false;
  13.  
  14. for (unsigned int x = 0; x < dupecheckVec.size(); x++)
  15. {
  16. if (concatVec[i] == dupecheckVec[x])
  17. {
  18. exists = true;
  19. }
  20. }
  21.  
  22. if (exists == false)
  23. {
  24. dupecheckVec.push_back(concatVec[i]);
  25. linenoVec.push_back(i);
  26. }
  27. else
  28. {
  29. exists = false;
  30. }
  31. }

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

在大文件中执行此操作可能不那么可怕?

解决方法

如果你不介意重新排序向量,那么这应该在O(n * log(n))时间内完成:
  1. std::sort(vector.begin(),vector.end());
  2. vector.erase(std::unique(vector.begin(),vector.end()),vector.end());

为了保留顺序,您可以改为使用(行号,字符串*)对的向量:按字符串排序,使用比较字符串内容的比较器进行单一化,最后按行号排序,沿着以下行:

  1. struct pair {int line,std::string const * string};
  2.  
  3. struct OrderByLine {
  4. bool operator()(pair const & x,pair const & y) {
  5. return x.line < y.line;
  6. }
  7. };
  8.  
  9. struct OrderByString {
  10. bool operator()(pair const & x,pair const & y) {
  11. return *x.string < *y.string;
  12. }
  13. };
  14.  
  15. struct StringEquals {
  16. bool operator()(pair const & x,pair const & y) {
  17. return *x.string == *y.string;
  18. }
  19. };
  20.  
  21. std::sort(vector.begin(),vector.end(),OrderByString());
  22. vector.erase(std::unique(vector.begin(),StringEquals()),vector.end());
  23. std::sort(vector.begin(),OrderByLine());

猜你在找的C&C++相关文章