const map的< call size()< string,vector< int> >引起错误 [英] call size() of const map<string,vector<int> > cause error

查看:119
本文介绍了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.

这篇关于const map的&lt; call size()&lt; string,vector&lt; int&gt; &gt;引起错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆