0

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 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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The solution is using const_iterator find(const Key&) const instead.
Thanks, that makes perfect sense :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.