Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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<size_t, unsigned int> > 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<size_t, unsigned int> >::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?

like image 723
Arvin Avatar asked Aug 30 '11 04:08

Arvin


1 Answers

Because m (and therefore m.ridx_) is const, you must use the std::map< size_type, std::pair<size_t, unsigned int> >::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++)
like image 195
bdonlan Avatar answered Nov 06 '22 16:11

bdonlan