获取C ++ map中的元素索引 [英] Get index of element in C++ map

查看:2460
本文介绍了获取C ++ map中的元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C ++应用程序中有一个名为 myMap std :: map ,我希望得到一个元素使用 myMap.find(key) myMap [key] 。但是,我还想在地图中获取该元素的索引。

I have a std::map called myMap in my C++ application, and I want to get an element using either myMap.find(key) or myMap[key]. However, I would also like to get the index of that element in the map.

std::map<string, int> myMap;
// Populate myMap with a bunch of items...
myElement = myMap["myKey"];
// Now I need to get the index of myElement in myMap

是否有干净这样做的方法是什么?

Is there a clean way to do that?

谢谢。

推荐答案

A std :: map 实际上没有索引,而是有一个键/值对的迭代器。这类似于索引,因为它表示集合中的排序位置,但它不是数字。要获取键/值对的迭代器,请使用 find 方法

A std::map doesn't really have an index, instead it has an iterator for a key / value pair. This is similar to an index in that it represents a position of sorts in the collection but it is not numeric. To get the iterator of a key / value pair use the find method

std::map<string, int>::iterator it = myMap.find("myKey");

这篇关于获取C ++ map中的元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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