2

I have the following code:

boost::unordered_map<std::string, int> map;
map["hello"]++;
map["world"]++;

for(boost::unordered_map<std::string, int>::iterator it = map.begin(); it < map.end(); it++){
    cout << map[it->first];
}

and when I try to compile I get the following error but have no idea why?

error: no match for ‘operator<’ in ‘it < map.boost::unordered::unordered_map<K, T, H, P, A>::end [with K = std::basic_string<char>, T = int, H = boost::hash<std::basic_string<char> >, P = std::equal_to<std::basic_string<char> >, A = std::allocator<std::pair<const std::basic_string<char>, int> >, boost::unordered::unordered_map<K, T, H, P, A>::iterator = boost::unordered::iterator_detail::iterator<boost::unordered::detail::ptr_node<std::pair<const std::basic_string<char>, int> >*, std::pair<const std::basic_string<char>, int> >]()
Aly
  • 15,865
  • 47
  • 119
  • 191

2 Answers2

5

Try:

it != map.end()

as the for loop termination condition (instead of it < map.end()).

Reunanen
  • 7,921
  • 2
  • 35
  • 57
4

In case of iterators you must use != operator:

boost::unordered_map<std::string, int>::iterator it = map.begin();
for(; it != map.end(); ++it){
    cout << map[it->first];
}

You cant use < because iterator points to memory, and you cant guarantee that memory is contiguous. That's why you MUST use != compare.

Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
  • The Vector iterator for example defines operator< so we can use this terminating condition. I guess it depends on how the iterator is implemented – Aly Oct 24 '12 at 12:16
  • Honestly didnt know about it but in other hand it's logical to use it for vector but i never seen this in use. Anyway looping always use != operator – Denis Ermolin Oct 24 '12 at 12:21
  • It is not anything about contiguous, the simple matter is that the standard declares that iterators should be comparable with != and == which are well defined as long as the iterators belong to the same collection and are in range (including one past the end). Where as the standard does not say operator< has to be supported between iterators, so boost didn't implement it in this case. – CashCow Oct 24 '12 at 12:26
  • Sure i said about memory to explain why iterator use != == for compare . Not special for boost – Denis Ermolin Oct 24 '12 at 12:28