【发布时间】:2015-08-05 16:37:44
【问题描述】:
程序将不同的字符串添加到集合中。迭代器检查某个字符串的集合,我想要实现的是获取迭代器找到这个特定字符串的行。是否有可能用一组来获得这个,还是我必须创建一个向量?我使用集合的原因是因为我也不想最后有重复。我知道这有点令人困惑,希望你能理解。
编辑:如果发现重复,我想获取集合中已经存在的原始元素的行号
#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;
}
【问题讨论】:
-
你到底想做什么。您的问题不清楚。
-
顺便说一句:insert 返回一个对,其中包含 first= 对插入元素的迭代器和 second= bool 如果元素已插入则为 true,如果已存在则为 false。所以
if (test.insert(cpstot).second){cout << "i: " << i << endl;}将替换test.find和it != test.end() -
问题:你要原件的行号还是找到的重复件的行号?
-
我想要集合中已经存在的原始元素的行号(这里应该是第 0 行,因为第 0 行是“1 2 3”,第 1 行是“4 5 6”并且然后第 3 行再次 "1 2 3")