Arv*_*vin 0 c++ map operator-keyword
我有一个有以下私人成员的班级:
private:
int *vals_;
size_type *cidx_;
std::map< size_type, std::pair<size_t, unsigned int> > ridx_;
Run Code Online (Sandbox Code Playgroud)
现在我试图在operator << overload中访问这些变量:(注意m是const)
std::ostream& operator<<(std::ostream &os, const SMatrix &m)
{
os << m.cidx_[0] << endl;
os << m.ridx_[0].first << endl;
return os;
}
Run Code Online (Sandbox Code Playgroud)
我发现m.cidx_ [0]会起作用,但m.ridx_ [0] .first会出错:
错误:将'const std :: map,std :: less,std :: allocator >>>'作为'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator []的'this'参数传递( const _Key&)[with _Key = unsigned int,_Tp = std :: pair,_Compare = std :: less,_Alloc = std :: allocator >>]'丢弃限定符
我认为这意味着operator []是一个修改操作符,因此与m是const的事实相矛盾.但是为什么它适用于vals_和cidx_,它们是int和size_type数组?
std::map::operator[]
如果元素不存在则插入元素,因此不能与const
对象一起使用.数组在C++中不是类类型,因为它们a[idx]
相当于*(a + idx)
并且从不改变数组本身.