[英]c++ unordered_map iterator on single object
I have a string and an unordered_map of (string, Object). 我有一个字符串和一个(string,Object)的unordered_map。 I already have some code in which I am iterating over the map:
我已经有一些代码在迭代地图:
for(auto& item : map) {
do_something;
}
I want to modify it to do the part inside the for loop when the string is non-empty and found inside the map else if string is empty do it for all items in the map. 我想修改它以在字符串非空时在for循环中执行部分并在map中找到else else如果string为空则对地图中的所有项执行此操作。
if(!string.empty()){
item = map.find(string);
do_something;
}
else {
for(auto& item : map) {
do_something;
}
}
Can I do this without rewriting the do_something or creating a separate function? 我可以在不重写do_something或创建单独的函数的情况下执行此操作吗?
To follow the line of thought you presented in the comments. 遵循您在评论中提出的思路。 You can replace the range for loop by a regular for loop over a specific range (defined by iterators).
您可以通过在特定范围(由迭代器定义)上的常规for循环替换循环范围。 To define it, you'd need something like this:
要定义它,你需要这样的东西:
auto begin = map.begin(), end = map.end(); // The whole map
if(!string.empty())
std::tie(begin, end) = map.equal_range(string);
// constrain range to the single element
for(; begin != end; ++begin) { // loop over it
auto& item = *begin;
// Do something
}
The star of the above is std::unordered_map::equal_range
. 上面的星是
std::unordered_map::equal_range
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.