首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >call size() of const map<string,vector<int> >call

call size() of const map<string,vector<int> >call
EN

Stack Overflow用户
提问于 2013-12-28 21:07:16
回答 4查看 2.5K关注 0票数 2
代码语言:javascript
复制
  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时,它是正常的。

EN

回答 4

Stack Overflow用户

发布于 2013-12-28 21:10:38

问题不在于对size()的调用。问题是在const映射上使用operator[]():如果键不存在,下标操作符将插入键,从而修改映射。要做到这一点,std::map<std::string, std::vector<int>>当然不能是const

如果您只想访问这些值,则需要直接使用find()

代码语言:javascript
复制
void example(std::map<std::string, std::vector<int>> const& num) {
    std::map<std::string, std::vector<int>>::const_iterator it(num.find("A"));
    if (it != num.end()) {
        std::cout << it->second.size() << '\n';
    }
    else {
        std::cout << "No key 'A` in the map\n";
    }
}

..。或者你可以使用at(),它会在访问一个不存在于非const映射中的键时抛出异常(感谢this指出的问题):

代码语言:javascript
复制
void example(std::map<std::string, std::vector<int>> const& num) {
    std::cout << num["A"].size() << '\n';
}
票数 2
EN

Stack Overflow用户

发布于 2013-12-28 21:40:01

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

代码语言:javascript
复制
T& operator[](const key_type& x);
T& operator[](key_type&& x);

正如您看到的,参数列表的闭括号后的限定符const是缺失的。然而,成员函数at是为const对象定义的(参见第二个声明)。

代码语言:javascript
复制
T& at(const key_type& x);
const T& at(const key_type& x) const;.

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

票数 1
EN

Stack Overflow用户

发布于 2013-12-28 21:30:28

函数num不知道已经在另一个函数中添加了一个键"A",如果没有,num["A"]会添加它。因此,要使用[],映射操作数不能为const

简而言之,这不是size()的错。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20814909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档