C ++迭代器到集合的最后一个元素 [英] C++ iterator to last element of a set

查看:155
本文介绍了C ++迭代器到集合的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中具有以下代码

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;
}

为什么总是打印"3"而不是集合中的最大元素?用cout << *--a.end();替换cout << *a.end();很好.

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

推荐答案

只需使用*a.rbegin()指向集合中的最后一个元素

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

这篇关于C ++迭代器到集合的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆