c++ - 从 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
它不是迭代器?我也不能递增/递减key
或val
(或者在这篇文章中使用 C++11 版本时),所以我猜它不算作迭代器?我不知道迭代器让我感到困惑。
这篇文章似乎是我想要的,但由于某种原因lower_bound()
无法使用oper_map
;没有合适的转换。
解决方案
不key
。不是迭代器。
for (auto const& [key, val] : oper_map)
key
是const
对映射中键的引用。如果您想要迭代器,请使用迭代器:
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
)。
推荐阅读
- java - 在 PayUCheckoutPro Payumoney PaymentGateways 集成中找不到明确的活动类
- r - 比较涉及整数和 NA 的评级
- swiftui - SpriteKit 场景中的幻像按钮
- selenium - Python Selenium:driver.quit() 无法清除临时文件
- sql-server - Service Broker : 多个源和一个目标...连接已关闭
- xamarin.forms - 如何在 xamarin 上制作半透明背景图像
- .net - 如何从 Visio 加载项中读取 Excel 单元格值作为字符串
- java - 与 scrollView 一起使用时,ViewPager 的内部内容不可见
- azure - 在不映射项目的情况下将文件添加到 Azure 存储库
- python - 网络抓取NBA结果