简体   繁体   中英

c++ unordered_map iterator on single object

I have a string and an unordered_map of (string, Object). 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.

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?

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). 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM