给定一个 std::set::iterator,获取一个指向下一个元素的迭代器
Given a std::set::iterator, get an iterator pointing to the next element
如果我有一个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
; 对于迭代器,这对于性能可能很重要,因为后缀增量必然使新的迭代器对象返回,而前缀增量可以更便宜地修改迭代器(仅返回对迭代器本身的引用,不需要副本)。
相关文章:
- 重新定位图像时如何前进到下一个内存块
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- CIN 仅在输入非数字值时跳过下一个 CIN
- 查找最小的下一个更大的元素
- 转到基于范围的 for 循环中的下一个迭代器
- 如何检查流中文件的下一个单词是否为 alpha?
- 如何打印下一个字母直到 Z 并继续到 A?
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 有没有一种标准方法可以在C++中获取第 n 个"下一个"浮点值
- 下一个云桌面客户端构建过程
- C++自定义流操纵器,用于更改流上的下一个字符串
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 下一个排列定义
- 查找下一个具有真值C++的数组索引
- 如何比较文件中包含的下一个字符
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- 当我使用c++生成器时,如何在输入完成后自动跳转到下一个"TEdit"
- 简单链表与下一个>下一个交换