首页 > 解决方案 > 从 for 循环中获取地图中的上一个或下一个项目

问题描述

我正在制作一个可以同时接受多个运算符的计算器(例如 5x5x5)。我有一张地图,其中包含操作员的位置以及它们的类型(x/+-)。我也有一个 for (auto const& [key, val] : oper_map)这篇文章中得到的 for 循环。

为了得到左右数字,我需要知道左右运算符在哪里。我试图使用std::prev和这样std::next的:key

int loper_pos = -1;
int roper_pos = 0;
double lnum;
double rnum;
char loper;
char roper;

//map defined elsewhere
for (auto const& [key, val] : oper_map)
{
    //loper is left operator while roper is right opeprator

    //tracks the position of the loop
    int map_pos = std::distance(oper_map.begin(), oper_map.find(key)); 

    if (map_pos == 0) loper_pos = -1;
    else
    {
        loper_pos = std::prev(key);
        loper = std::prev(val);
    }
    if (map_pos == oper_map.size()) roper_pos = oper_map.size() + 1;
    else
    {
        roper_pos = std::next(key);
        roper = std::next(val);
    }

但我想它不起作用,因为key它不是迭代器?我也不能递增/递减keyval(或者在这篇文章中使用 C++11 版本时),所以我猜它不算作迭代器?我不知道迭代器让我感到困惑。

这篇文章似乎是我想要的,但由于某种原因lower_bound()无法使用oper_map;没有合适的转换。

标签: c++for-loopiteratorstdmap

解决方案


key。不是迭代器。

for (auto const& [key, val] : oper_map)

keyconst对映射中键的引用。如果您想要迭代器,请使用迭代器:

for (auto it = oper_map.begin(); it != oper_map.end(); ++it) {
    auto next = std::next(it);
    auto prev = std::prev(it);
}

但是,请考虑这std::map不是一个顺序容器。如果您对容器中元素的位置感兴趣,也许 astd::vector< std::pair<Key,MappedValue>>更方便(请注意,std::next对于双向迭代器(map),复杂性是线性的,而对于随机访问迭代器(向量),它是恒定的,对于 也是如此std::prev)。


推荐阅读