为什么set(c++)中的迭代器不能正常工作

Why is iterator in set(c++) not behaving properly?

本文关键字:常工作 工作 不能 set c++ 为什么 迭代器      更新时间:2023-10-16

这是我写的代码:

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)

根据注释更新