通过索引访问地图值 [英] Accessing map value by index

查看:79
本文介绍了通过索引访问地图值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的结构

std::map<string, int> myMap;
myMap["banana"] = 1;
myMap["apple"] = 1;
myMap["orange"] = 1;

如何访问myMap [0]?

How can I access myMap[0]?

我知道地图在内部进行排序,对此我很好,我想按索引在地图中获取一个值.我已经尝试过myMap [0],但收到错误消息:

I know that the map sorts internally and I'm fine with this, I want to get a value in the map by index. I've tried myMap[0] but I get the error:

Error   1   error C2679: binary '[' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)   

我意识到我可以做这样的事情:

I realise I could do something like this:

string getKeyAtIndex (int index){
    map<string, int>::const_iterator end = myMap.end(); 

    int counter = 0;
    for (map<string, int>::const_iterator it = myMap.begin(); it != end; ++it) {
        counter++;

        if (counter == index)
            return it->first;
    }
}

但是可以肯定,这是非常低效的吗?有没有更好的办法?

But surely this is hugely inefficient? Is there a better way?

推荐答案

不应以这种方式访问​​您的map,它是通过键而不是位置来索引的. map迭代器是双向的,就像list一样,因此所使用的函数的效率没有比按位置访问list的效率低.从begin()开始,可以在std::advance( iter, index )的帮助下编写函数.如果要按位置随机访问,请使用vectordeque.

Your map is not supposed to be accessed that way, it's indexed by keys not by positions. A map iterator is bidirectional, just like a list, so the function you are using is no more inefficient than accessing a list by position. Your function could be written with help from std::advance( iter, index ) starting from begin(). If you want random access by position then use a vector or a deque.

这篇关于通过索引访问地图值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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