c++ - How to access a range/interval of keys in an ordered map in C++?
问题描述
I am trying to write an if-condition where I want to execute code depending on which elements of a map are accessed, e.g. for a map with 100 elements only for elements 26 to 74. But I do not want to address specific keys but rather a certain fraction of the map. Should I do this with the []
operator? I tried
if(map.size()/4 < iterator < map.size()*3/4){}
but this does not work.
解决方案
只需将迭代器获取到您要检查的范围的开头和结尾,例如
auto it = std::next(map.begin(), map.size() / 4);
auto end = std::next(map.begin(), map.size() * 3 / 4);
然后你可以像这样迭代那个范围
for (; it != end; ++it)
{
// do stuff here
}
如果你想要一个计数器,你甚至不需要 end 迭代器。这可以节省您在地图中推进结束迭代器的成本,这可能会有所作为,尤其是在较大的地图上。那看起来像
auto it = std::next(map.begin(), map.size() / 4);
auto end = map.size() / 2;
for (size_t counter = 0; counter < end; ++it, ++counter)
{
// do stuff here
}
推荐阅读
- javascript - 一次提交多个表单时防止页面重新加载的更好方法?
- mysql - 插入触发器错误 #1064 sql person_info 和 Total_bank
- bash - 如何使用 gnu parallel 或任何其他并行运行多个 bash 脚本
- android - 文档快照的工作原理
- javascript -
TypeError:无法读取未定义的属性“成员” - c++ - 如何正确导入 windows.h 作为模块
- angular - Angular Material Cards 不会填满整行
- architecture - 触发日常任务的服务消费者 - 架构
- amazon-web-services - PySpark 读取 DynamoDB 格式的 json
- javascript - 输入框中的数字添加空格分隔符,并保存光标