Why operator[] not allowed for maps but are allowed for int arrays?
I have a class with the following private members:
private:
int *vals_;
size_type *cidx_;
std::map< size_type, std::pair<size_t, unsigned int> > ridx_;
Now I am trying to access these variables in operator<< overload: (Note that m is const)
std::ostream& operator<<(std::ostream &os, const SMatrix &m)
{
os << m.cidx_[0] << endl;
os << m.ridx_[0].first << endl;
return os;
}
What I find is m.cidx_[0] will work, but m.ridx_[0].first gives an error:
error: passing 'const std::map, std::less, std::allocator > > >' as 'this' argument 开发者_JAVA技巧of '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = unsigned int, _Tp = std::pair, _Compare = std::less, _Alloc = std::allocator > >]' discards qualifiers
Which I believe means operator[] is a modifying operator and hence contradicts the fact that m is const. But why does it work for vals_ and cidx_ which are int and size_type arrays?
std::map::operator[]
inserts an element if it doesn't exist, so it cannot be used with const
objects. Arrays are not class types in C++, for them a[idx]
is equivalent to *(a + idx)
and never mutates the array by itself.
if you look through the source code of map container, there is no map::operator [] with const cv qualifier, but your matrix object is const
精彩评论