简体   繁体   English

C ++中集合中的迭代器

[英]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. 但是,当我更换arr.begin()arr.end()我没有得到最大的元素。 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. end迭代器实际上不在容器内部,而是“指向”容器之外的一个位置。 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). 请记住,数组索引是从零开始的,上述数组的有效索引将是03 (含3 )。 The "begin" iterator for the array would be &a[0] and the "end" iterator would be &a[4] . 数组的“开始”迭代器为&a[0] ,“结束”迭代器为&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: 如果使用反向迭代器(带有std::set::rbeginstd::set::rend ),则将是这样的:

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

But when I replace arr.begin() with arr.end() I don't get the largest element. 但是,当我更换arr.begin()arr.end()我没有得到最大的元素。

That's because end() "points to" one element past the last element of the set. 这是因为end() “指向”集合最后一个元素之后的一个元素。

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. 您需要arr.rbegin() ,它指向另一端的第一个元素,即正确的最后一个元素。 The type is going to change from set<int>::iterator to set<int>::reverse_iterator . 类型将从set<int>::iterator更改为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. 如果使用C ++ 11,则使用auto而不是显式类型将帮助您隐藏类型中的更改。

使用std::set::rbegin

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

Dereferencing std::set::end() results in undefined behaviour. 取消引用std::set::end()导致未定义的行为。

If you want the greatest element, assuming standard ordering using less<int> , use rbegin() . 如果您需要最大的元素,则假设使用less<int>标准排序,请使用rbegin()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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