C++ 集合、迭代器、查找重复行的用法

C++ Usage of set, iterator, find line where duplicate was found

该程序将不同的字符串添加到一组中。迭代器检查某个字符串的集合,我想要实现的是获取迭代器找到这个特定字符串的行。是否可以用一组来获得它,还是我必须创建一个矢量?我使用集合的原因是因为我也不想最后有重复项。我知道这有点令人困惑,希望你能理解。

编辑:如果找到重复项,我想获取集合中已存在的原始元素的行号

#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <atlstr.h>
#include <sstream>

using namespace std;  

int _tmain(int argc, _TCHAR* argv[])
{
set<string> test;
set<string>::iterator it;
vector<int> crossproduct(9, 0);

for (int i = 0; i < 6; i++)
{
    crossproduct[i] = i+1;
}

crossproduct[6] = 1;
crossproduct[7] = 2;
crossproduct[8] = 3;


for (int i = 0; i < 3; i++)
{
    ostringstream cp; cp.precision(1); cp << fixed;
    ostringstream cp1; cp1.precision(1); cp1 << fixed;
    ostringstream cp2; cp2.precision(1); cp2 << fixed;

    cp << crossproduct[i*3];
    cp1 << crossproduct[i*3+1];
    cp2 << crossproduct[i*3+2];

    string cps(cp.str());
    string cps1(cp1.str());
    string cps2(cp2.str());

    string cpstot = cps + " " + cps1 + " " + cps2;

    cout << "cpstot: " << cpstot << endl;

    it = test.find(cpstot);     

    if (it != test.end())
        {
            //Display here the line where "1 2 3" was found
            cout << "i: " << i << endl;
        }


    test.insert(cpstot);
}

set<string>::iterator it2;

for (it2 = test.begin(); it2 != test.end(); ++it2)
{
    cout << *it2 << endl;
}

cin.get();

return 0;
}

"Line number"对一个std::set<string>意义不大, 因为当您向集合中添加更多字符串时,您可能会更改 迭代现有字符串的顺序 (这与 set::set 模板差不多 "line number" 它自己会给你)。

这里有一个可能效果更好的替代方案: std::map<std::string, int> test。 你使用它的方式是在某处保留一个 "line counter" n。 每次你需要在你的集合中放入一个新字符串 cpstot 时, 你有这样的代码:

  std::map<std::string>::iterator it = test.find(cpstot);
  if (it == test.end())
  {
    test[cpstot] = n;
    // alternatively, test.insert(std::pair<std::string, int>(cpstot, n))
    ++n;
  }
  else
  {
    // this prints out the integer that was associated with cpstot in the map
    std::cout << "i: " << it->second;

    // Notice that we don't try to insert cpstot into the map in this case.
    // It's already there, and we don't want to change its "line number",
    // so there is nothing good we can accomplish by an insertion.
    // It's a waste of effort to even try.
  }

如果在开始将任何字符串放入 test 之前设置 n = 0,则 (并且不要以任何其他方式混淆 n 的值) 那么你将在 "line numbers" 0、1、2 等处得到字符串。 在 testn 中将存储在 test.

中的字符串数

顺便说一下,std::map<std::string, int>::iteratorstd::set<std::string>::iterator 保证遍历 按照它们首次插入的顺序排列的字符串。 相反,你会得到的是字符串的任何顺序 模板的比较对象放置字符串值。 (我想默认情况下你会按照字典顺序把它们取回来, 即 "alphabetized"。) 但是当您将每个字符串的原始 "line number" 存储在 std::map<std::string, int> test,当你准备好 打印出可以复制字符串-整数对的字符串列表 从 test 到新对象 std::map<int, std::string> output_sequence, 现在(假设您没有覆盖默认比较对象) 当你遍历 output_sequence 你会得到它 内容按行号排序。 (然后您可能想要获取字符串 来自迭代器的 second 字段。)