0

I'm trying to update a key in a nested map if it exists or insert it if it doesn't. I'm trying to use an iterator with lower_bound to make this process efficient.

std::unordered_map<std::string, std::unordered_map<std::string, std::string>> maps; cache::iterator iter(maps[command[1]].lower_bound(command[2])); if (iter == maps[command[1]].end() || command[2] < iter->first) { maps[command[1]].insert(iter, std::make_pair(command[2], command[3])); } else { iter->second = command[3]; } 

I'm getting the following compile time error: no member named 'lower_bound' in 'std::unordered_map<std::basic_string<char>, std::basic_string<char>, std::hash<std::string>, std::equal_to<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >'

5
  • That's because std::unordered_map::lower_bound doesn't exist! It doesn't make sense to look for a lower bound on a container where the elements aren't sorted. Commented Mar 29, 2019 at 16:00
  • So is there no efficient way to solve this? Commented Mar 29, 2019 at 16:01
  • 1
    What is wrong with using find to see if the element exists? Commented Mar 29, 2019 at 16:06
  • An insert hint is not really useful on a hash-based container (unless the new element hashes to the same as the element pointed to by the hint, which would basically mean it is the same element, in which case you wouldn't be inserting anyway). Commented Mar 29, 2019 at 16:08
  • stackoverflow.com/q/15559655 Commented Mar 29, 2019 at 16:27

1 Answer 1

1

As the name suggests, unordered_map is not ordered in any particular way. Because lower_bound methods and functions refer to the order of elements, they make sense only on ordered data. That's why there is no such method for unordered_map.

Many benchmarks on many compilers have shown that an std::map, with fewer that a thousand elements, is significantly faster than std::unordered_map. This means that you should consider switching to an std::map, or use the following:

maps[command[1]].insert_or_assign(command[2], command[3]); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.