如果我有一个std::set::iterator
,如何快速生成指向集合中下一个元素的迭代器?此一般问题的具体用例如下:
假设我有一个std::set
,我想打印出集合中的所有不同元素对。我相信我不能写my_set.begin() + 1
这样的东西,因为set
产生的迭代器不能算术(不像vector
产生的迭代器)。那么我该如何才能做到这一点呢?
我想出的解决方案是
int main(){
set<int> my_set {1,4,6};
for (auto it = my_set.begin(); it != my_set.end(); it++) {
int first_number = *it;
for (auto it2 = it; it2!= my_set.end(); it2++) {
if (it2 == it){it2++;} // I don't want the second number to be equal to the first
if (it2 == my_set.end()) {break;} //If I don't put this in, it will eventually try to access my_set.end(), giving bad behavior.
int second_number = *it2;
cout << "(" << first_number << ", " << second_number << ")" << endl;
}
}
return 0;
}
输出:
(1, 4)
(1, 6)
(4, 6)
Program ended with exit code: 0
但我认为,必须手动迭代它2,然后检查它是否my_set.end()
,这很笨拙。我怎样才能做得更好?
我尝试使it2循环看起来像
for (auto it2 == it; it2!= my_set.end(); it2++) {...
使它以it2
大于it
的语法开始,但它对这种语法不满意。
如果这个问题以前出现过,我们深表歉意。我找不到它。
std::next
可用于在一次调用中获取相对于现有迭代器高级的新迭代器(如果未传递第二个参数,则它只前进一次),因此您的代码应该只需:
#include <iterator> // For std::next
int main(){
set<int> my_set {1,4,6};
for (auto it = my_set.begin(); it != my_set.end(); ++it) {
int first_number = *it;
for (auto it2 = std::next(it); it2 != my_set.end(); ++it2) {
int second_number = *it2;
cout << "(" << first_number << ", " << second_number << ")" << endl;
}
}
return 0;
}
在线试用!
请注意,我还将您的it++
/it2++
表达式更改为++it
/++it2
; 对于迭代器,这对于性能可能很重要,因为后缀增量必然使新的迭代器对象返回,而前缀增量可以更便宜地修改迭代器(仅返回对迭代器本身的引用,不需要副本)。