首页 > 解决方案 > 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.

标签: c++dictionary

解决方案


只需将迭代器获取到您要检查的范围的开头和结尾,例如

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
}

推荐阅读