【问题标题】:"No match for operator=" trying to iterate through map in C++“运算符不匹配 =” 尝试在 C++ 中遍历映射
【发布时间】:2011-11-06 12:06:01
【问题描述】:

我正在尝试遍历定义如下的地图:

std::map< size_type, std::pair<size_t, unsigned int> > ridx_;

现在我正在尝试在以下重载运算符的友元函数中迭代 ridx_(它是类的私有成员)

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;
}

但是 g++ 错误:

SMatrix.cpp:34: 错误: 'it = 中的'operator=' 不匹配 m->SMatrix::ridx_.std::map<_key _tp _compare _alloc>::begin with _Key = 无符号整数,_Tp = std::pair, _Compare = std::less, _Alloc = std::allocator > >' /usr/include/c++/4.3/bits/stl_tree.h:152:注意: 候选人是:std::_Rb_tree_iterator > >& std::_Rb_tree_iterator >>::operator=(const std::_Rb_tree_iterator > >&) make: * [myTest] 错误 1

我做错了什么?

【问题讨论】:

    标签: c++ map iterator compiler-errors constants


    【解决方案1】:

    因为m(因此m.ridx_)是常量,所以这里必须使用std::map&lt; size_type, std::pair&lt;size_t, unsigned int&gt; &gt;::const_iterator,而不是::iterator

    如果您使用的是 C++0x 编译器,您可能还需要考虑使用 auto

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

    【讨论】:

    • 我梦想有一天错误消息可以被不太熟悉 c++ 的人阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多