【发布时间】:2021-02-07 01:37:59
【问题描述】:
如果我有这样的结构
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;
}
}
但这肯定是非常低效的吗?有没有更好的办法?
【问题讨论】: