const map的< call size()< string,vector< int> >引起错误

问题描述:

  void example(const map<string, vector<int> > & num);

  int main()
  {
      map<string, vector<int> >num;

      num["A"].push_back(1);
      example(num);

      return 0;
  }

  void example(const map<string, vector<int> > & num)
  {
      cout <<  num["A"].size() << endl;
  }



我认为size()没有改变num的值,它会导致错误当完全?
当我删除示例函数中的关键字const时,它是确定。

i think the size() did not change the value of num, but why it cause error when complie it? it's ok when i removed the keyword const in the example function.

问题是operator [没有为std :: map类型的const对象定义。这里是运算符的声明

The problem is that operator [] is not defined for const objects of type std::map. Here are declarations of the operator

T& operator[](const key_type& x);
T& operator[](key_type&& x);

正如你看到参数列表右括号后的限定符const不存在。但是成员函数at是为const对象定义的(见第二个声明)

As you see the qualifier const after the closing parenthesis of the parameter list is absent. However member function at is defined for const objects (see the second declaration)

T& at(const key_type& x);
const T& at(const key_type& x) const;.

因此,您不能使用下标运算符,而必须使用成员函数。

So instead of the subscript operator you must use member function at.