krizzo
krizzo

Reputation: 1883

Iterate through a map of lists?

I have a map<string, list<int> > which I want to iterate over the list and print out each number. I keep getting a compile error talking about conversion between a const_iterator and iterator. What am I doing wrong with this?

for (map<string, list<int> >::iterator it = words.begin(); it != words.end(); it++)
{
   cout << it->first << ":";
   for (list<int>::iterator lit = it->second.begin(); lit  != it->second.end(); lit++)
      cout << " " << intToStr(*lit);
   cout << "\n";
}

error: conversion from
  ‘std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::list<int, std::allocator<int> > > >’
to non-scalar type
  ‘std::_Rb_tree_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::list<int, std::allocator<int> > > >’
requested|

Upvotes: 1

Views: 4403

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258568

map<string, list<int> >::iterator

should be

map<string, list<int> >::const_iterator

Either your map is const, or your map is a member of a class and you're calling this code in a const function, which also makes your map const. Either way, you can't have a non-const operator on a const container.

EDIT: Am I the only one who prefers to use explicit types over auto?

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168616

Try to use the new C++11 range-based for loop:

for(auto& pair : words) {
  std::cout << pair.first << ":";
  for(auto& i : pair.second) {
    std::cout << " " << intToStr(i);
  }
  std::cout << "\n";
}

Upvotes: 3

TemplateRex
TemplateRex

Reputation: 70516

Try to use the new C++11 auto keyword

for (auto it = words.begin(); it != words.end(); it++)
{
   cout << it->first << ":";
   for (auto lit = it->second.begin(); lit  != it->second.end(); lit++)
      cout << " " << intToStr(*lit);
   cout << "\n";
}

If you still get errors, you have defined inconsistent types.

Upvotes: 4

Related Questions