C ++使用set,iterator,查找找到重复的行

时间:2015-08-05 16:37:44

标签: c++ iterator set

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

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

#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;
}

1 个答案:

答案 0 :(得分:2)

&#34;行号&#34;对std::set<string>没有意义, 因为当您向集合添加更多字符串时,您可能会更改 迭代现有字符串的顺序 (与set::set模板大致相同的&#34;行号和#34; 本身会给你)。

这是一个可能更好的替代方案: std::map<std::string, int> test。 你使用它的方式是保持一个&#34;行计数器&#34; 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.
  }

如果您在开始在n = 0中添加任何字符串之前设置test (并且不要以任何其他方式混淆n的价值) 那么你最终会得到&#34;行号&#34; 0,1,2等 在testn中将是test中存储的字符串数。

顺便说一句,std::map<std::string, int>::iterator也没有。{ 保证std::set<std::string>::iterator可以迭代 它们首次插入的序列中的字符串。 相反,你得到的是无论以何种顺序排列的字符串 模板的比较对象放置字符串值。 (我认为默认情况下你会按字典顺序取回它们, 也就是说,&#34;按字母顺序排列&#34;。) 但是当你存储原始的&#34;行号&#34;每个字符串中的 std::map<std::string, int> test,当你准备好的时候 打印出可以复制字符串 - 整数对的字符串列表 从test到新对象std::map<int, std::string> output_sequence, 现在(假设你没有覆盖默认的比较对象) 当你遍历output_sequence时,你会得到它 内容按行号排序。 (然后你可能想要得到字符串 来自迭代器的second字段。)