通过索引访问地图值
如果我有这样的结构
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 )
的帮助下编写函数.如果要按位置随机访问,请使用vector
或deque
.
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
.