2011-08-30 49 views
4

我試圖通過定義爲下面的一個地圖迭代迭代:「不匹配操作員=」試圖通過在地圖C++

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

然而克++有錯誤出來:

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

我在做什麼錯?

回答

12

因爲m(因此m.ridx_)是常量,所以您必須在此處使用std::map< size_type, std::pair<size_t, unsigned int> >::const_iterator而不是::iterator

如果您正在使用的C++ 0x編譯器,你可能要考慮使用auto還有:

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

啊,我明白了,謝謝堆! – Arvin

+1

我夢想有一天,錯誤消息可以被熟悉C++的人所不熟悉的人閱讀。 – 2017-04-03 17:16:24