为什么set(c++)中的迭代器不能正常工作
Why is iterator in set(c++) not behaving properly?
这是我写的代码:
multiset<int>S;
for(int i = 0;i<20;i++)
S.insert(i);
for(auto it = S.end();it!=S.begin();--it)
cout<<*it<<" ";
cout<<endl;
输出:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
您的代码包含一些未定义的行为。正如您已经指出的,S将包含从0到20(不包括)的所有值,尽管不知怎的打印给出了1到20(包括)。
代码:for(auto it = S.end();it!=S.begin();--it)
cout<<*it<<" ";
这里的问题是范围[begin, end)
有end
指向不属于集合的东西。对end()接收到的迭代器解引用可能导致程序崩溃,或者让它产生一些随机值。在这种情况下,我猜你得到的值是20,因为编译器优化了。(一些黑盒优化)
在c++(和其他语言)中,迭代器的概念伴随着反向迭代器的概念。(如果你点击链接,有一张解释迭代器的漂亮图片。)
基本上,使用反向迭代器可以让你从后面循环到开始,就像使用普通迭代器一样:
for (auto it = S.crbegin(); it != S.crend(); ++it)
cout << *it << " ";
注意,rbegin()和crbegin()在代码复杂性方面没有任何缺点。(除非你想再次将它们转换为正向迭代器)
附加:默认情况下,不要在迭代器上使用——操作符,它会在调试时让人头疼。
带迭代器的循环是不正确的,并且具有未定义的行为,因为成员函数end()返回的迭代器在循环中被解引用。
一个有效的程序可以像
#include <iostream>
#include <set>
int main()
{
std::multiset<int> s;
for ( int i = 0; i < 20; i++ ) s.insert( i );
for ( auto it = s.end(); it != s.begin(); ) std::cout << *--it << " ";
std::cout << std::endl;
return 0;
}
输出为
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
当然可以使用函数rbegin()
返回的类的反向迭代器。例如
#include <iostream>
#include <set>
int main()
{
std::multiset<int> s;
for ( int i = 0; i < 20; i++ ) s.insert( i );
for ( auto it = s.rbegin(); it != s.rend(); ++it ) std::cout << *it << " ";
std::cout << std::endl;
return 0;
}
在这种情况下,循环看起来更简单。
更好的使用:
for(auto it = S.rbegin(); it != S.rend(); ++it)
根据注释更新
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- C++程序已停止工作-求解常微分方程