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

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

本文关键字:用法 发现 集合 迭代器 查找 C++      更新时间:2023-10-16

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

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

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

"行号"对std::set<string>不是很有意义,因为当您向集合中添加更多字符串时,您可能会更改现有字符串的迭代顺序(这与set::set模板的"行号"差不多本身会给你(。

这是一个可能效果更好的替代方案: std::map<std::string, int> test .你使用它的方式是你在某处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的价值(然后你最终会在"行号"0、1、2 等处得到字符串。在testn中将是存储在test中的字符串数量。

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