Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 571
250 Avatar asked Aug 05 '26 01:08

250


1 Answers

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.

like image 123
StoryTeller - Unslander Monica Avatar answered Aug 07 '26 20:08

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!