简体   繁体   中英

Iterators in sets in C++

#include<iostream>
#include<set>
using namespace std;

set <int> arr;

int main() {
int n, m, tmp;
cin>>n>>m;
for (int i=1; i<=m+n; i++) {
    cin>>tmp;
    if (tmp!=-1) arr.insert(tmp);
    else {
        set<int>::iterator it;
        it=arr.begin();
        cout<<*it<<endl;
        arr.erase(arr.begin());
    }
}
return 0;
}

So this program actually outputs the smallest element present in the set. But when I replace arr.begin() with arr.end() I don't get the largest element. I need help in understanding what is happening and what should I do to output the largest number in the set

The end iterator is not actually inside the container, but "points" to one place beyond the end of the container. Dereferencing an iterator outside of the container leads to undefined behavior .


Pretend you have the array

int a[] = { 1, 2, 3, 4 };

Remembering that array indexes are zero-based, the valid indexes for the above array would be 0 to 3 (inclusive). The "begin" iterator for the array would be &a[0] and the "end" iterator would be &a[4] .

Or graphically it would be something like this:

+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
^               ^
|               |
begin           end

If using reverse iterators (with std::set::rbegin and std::set::rend ) then it would be something like this:

+---+---+---+---+
    | 1 | 2 | 3 | 4 |
    +---+---+---+---+
^               ^
|               |
rend            rbegin

But when I replace arr.begin() with arr.end() I don't get the largest element.

That's because end() "points to" one element past the last element of the set.

what should I do to output the largest number in the set

You need arr.rbegin() , which points to the first element from the other end, ie to the last element proper. The type is going to change from set<int>::iterator to set<int>::reverse_iterator . If you use C++11, using auto instead of the explicit type would help you hide the change in the type.

使用std::set::rbegin

            set<int>::reverse_iterator it=arr.rbegin();

Dereferencing std::set::end() results in undefined behaviour.

If you want the greatest element, assuming standard ordering using less<int> , use rbegin() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM