Reputation: 1883
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
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
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
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