假设我有一个向量{1,3,1,5,4,2,3,4,5,2}
(向量大小可能非常大),
indices --> 1 2 3 4 5 6 7 8 9 10
values --> 1 3 1 5 4 2 3 4 5 2
其关系如下:
1 --> {1,3}
2 --> {6,10}
3 --> {2,7}
4 --> {5,8}
5 --> {4,9}
现在使用set,我可以将其缩小为{1,2,3,4,5}
,
std::set<int> uniqNumbersSet;
for(unsigned int i = 0; i < uniqNumbers.size(); ++i )
{
uniqNumbersSet.insert(uniqNumbers[i]);
}
uniqNumbers.assign(uniqNumbersSet.begin(), uniqNumbersSet.end());
但我怎样才能跟踪他们原来的关系?使用STL的任何有效方法?
答案 0 :(得分:1)
您可以map
使用vector
。
#include <map>
#include <vector>
std::map<int, std::vector<unsigned> > uniqNumMap;
for (unsigned i = 0; i < uniqNumbers.size(); ++i) {
uniqNumMap[uniqNumbers[i]].push_back(i+1);
}
for (std::map<int, std::vector<unsigned> >::const_iterator i = uniqNumMap.begin(); i != uniqNumMap.end(); ++i) {
std::cout << i->first << " --> {";
for (std::vector<unsigned>::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
if (j != i->second.begin()) std::cout << ",";
std::cout << *j;
}
std::cout << "}\n";
}