std::map 中的最后一个键

发布于 2024-07-09 02:32:15 字数 190 浏览 6 评论 0原文

我正在寻找 std::map 的最高键值(由比较运算符定义)。

这保证是吗

map.rbegin()->first

(我对反向迭代器有点犹豫,以及 std::map 的实现有多少自由度)

如果没有,请告知。 我无法更改数据结构。

I am looking for the highest key value (a defined by the comparison operator) of a std::map.

Is this guaranteed to be

map.rbegin()->first

?

(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map)

If not, please advise. I cannot change the data structure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

枉心 2024-07-16 02:32:16

是的,但请记住检查 map.rbegin() != map.rend()

Yes, but remember to check that map.rbegin() != map.rend().

轻拂→两袖风尘 2024-07-16 02:32:16

您可以使用以下方法:-

if(!map.empty())
    (--map.end())->first;

You can use following method :-

if(!map.empty())
    (--map.end())->first;
一紙繁鸢 2024-07-16 02:32:16

还有一种方法——

std::prev(map.end())->first;

One more way -

std::prev(map.end())->first;
糖果控 2024-07-16 02:32:16

Map 按排序顺序存储键值对,以便我们可以通过以下方式访问最后一个元素:-

auto it=m.end();
it--;
int element=it->first;

Map store the key value pairs in sorted order so we can access the last element by :-

auto it=m.end();
it--;
int element=it->first;
夜访吸血鬼 2024-07-16 02:32:15

是的。 Map 是一个排序容器,反向迭代器必须按其键的相反(即递减)顺序返回元素。

[编辑:正如查尔斯·贝利在他的回答中指出的那样,您的代码给出了最大的键如果存在 - 即如果地图非空]

Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.

[Edit: as Charles Bailey points out in his answer, your code gives the greatest key if it exists - i.e. if the map is non-empty]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文