访问映射值如果我有一个像通过索引
std::map<string, int> myMap;
myMap["banana"] = 1;
myMap["apple"] = 1;
myMap["orange"] = 1;
如何访问MYMAP结构[0]?
我知道地图内部排序,我很好,我想通过索引得到地图中的值。我试过MYMAP [0],但我得到的错误:
Error 1 error C2679: binary '[' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
我知道我可以做这样的事情:
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;
}
}
但可以肯定,这是效率非常低?有没有更好的办法?
我现在看到的...你想随机访问。索引0只是一个例子,而不是实际的目标。 –