Friday, 11 November 2016

"No match for operator=" trying to iterate through map in C++



I'm trying to iterate through a map defined as the following:



std::map< size_type, std::pair > ridx_;



Now I'm trying to iterate through ridx_ (which is a private member of a class) in the following friend function which overloads operator<<



std::ostream& operator<<(std::ostream &os, const SMatrix &m) 
{
std::map< size_type, std::pair >::iterator it;

//The following is line 34
for (it = m.ridx_.begin(); it != m.ridx_.end(); it++)

os << it->first << endl;

return os;
}


However g++ errors out with:




SMatrix.cpp:34: error: no match for 'operator=' in 'it =

m->SMatrix::ridx_.std::map<_Key, _Tp, _Compare, _Alloc>::begin with
_Key = unsigned int, _Tp = std::pair,
_Compare = std::less, _Alloc =
std::allocator > >' /usr/include/c++/4.3/bits/stl_tree.h:152: note:
candidates are: std::_Rb_tree_iterator > >&
std::_Rb_tree_iterator > >::operator=(const
std::_Rb_tree_iterator > >&) make: * [myTest] Error 1




What am I doing wrong?



Answer



Because m (and therefore m.ridx_) is const, you must use the std::map< size_type, std::pair >::const_iterator, not ::iterator here.



If you're using a C++0x compiler, you might want to consider using auto as well:



for (auto it = m.ridx_.begin(); it != m.ridx_.end(); it++)

No comments:

Post a Comment