C++ iterator to last element of a set

∥☆過路亽.° 提交于 2019-12-19 09:24:17

问题


I have the following code in C++

#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> a;
    int n;

    for(int i=0;i<3;i++){
    cin>>n;
    a.insert(n);
    }

    cout << *a.end();
    return 0;
}

Why is it always printing "3" instead of the greatest element in the set? Replacing cout << *a.end(); with cout << *--a.end(); works fine.


回答1:


Why is it always printing "3" instead of the greatest element in the set?

Because a.end() is one past the end of your vector. It doesn't hold any valid data, it's a marker for the end of your vector. As in:

for(auto i = a.begin(); i != a.end(); ++i) 
    // do stuff with i

EDIT: (thanks to Nathan) dereferencing a.end() yields the dreaded undefined behaviour. Anything could have happened: get a 3, get the last element in the set, could even have canceled X-mas!!!




回答2:


*a.end()

Undefined behaviour. In C++ iterator terminology, "end" does not mean the same thing as "last element".

Replacing cout << *a.end(); with cout << *--a.end(); works fine.

Consider a reverse iterator: *a.rbegin().

Keep in mind that both begin() and rbegin() only return dereferencable iterators if the container is not empty. For empty containers, begin() == end() and rbegin() == rend().




回答3:


Just use *a.rbegin() which points to the last element in the set



来源:https://stackoverflow.com/questions/41302441/c-iterator-to-last-element-of-a-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!