按索引访问地图值

Sam*_*Sam 14 c++ stl map

如果我有一个像这样的结构

std::map<string, int> myMap;
myMap["banana"] = 1;
myMap["apple"] = 1;
myMap["orange"] = 1;
Run Code Online (Sandbox Code Playgroud)

如何访问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)   
Run Code Online (Sandbox Code Playgroud)

我意识到我可以这样做:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

K-b*_*llo 24

map不应该以这种方式访问​​,它由键而不是位置索引.一个map迭代器是双向的,就像一个list,所以你正在使用的功能并不比访问效率较低list的位置.您的功能可以在std::advance( iter, index )开始时帮助编写begin().如果你想按位置随机访问,那么使用a vector或a deque.


Tho*_*ews 6

可能有一种特定于实现的(非便携式)方法可以实现您的目标,但不是一种可移植的方法。

通常,将std::map其实现为一种二叉树,通常按关键字排序。第一个元素的定义因顺序而异。另外,在您的定义中,element [0]是树顶部还是最左侧叶节点的节点?

许多二进制树被实现为链接列表。大多数链接列表不能像数组一样直接访问,因为要找到元素5,必须遵循链接。这是根据定义。

您可以同时使用a std::vector和a 解决您的问题std::map

  1. 从动态内存分配对象。
  2. 将指针和键一起存储到中std::map
  3. 将指针存储在所需std::vector的位置。

std::map将允许通过键访问对象的有效方法。
std::vector将允许一种有效的方法来按索引访问对象。存储指针只允许对象的一个​​实例,而不必维护多个副本。

  • 那么当您需要向映射中插入新元素时,您该如何处理向量呢? (2认同)