c++ - 调用 const map<string,vector<int>> 的 size() 会导致错误

标签 c++ dictionary

  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 时就可以了。

最佳答案

问题不在于对 size() 的调用。问题是使用 operator[]()const上映射:如果键不存在,下标运算符将插入键,从而修改映射。为此,std::map<std::string, std::vector<int>>不可能const ,当然。

如果您只想访问需要使用的值 find()直接:

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 上不存在的 key 时,这将引发异常 map (感谢竹子指出this问题):

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

关于c++ - 调用 const map<string,vector<int>> 的 size() 会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814909/

相关文章:

c++ - C++:如何在Windows 10上使用编译器MinGW 9.2.0安装OpenCV

c++ - 释放动态内存

类内的Python多处理共享字典

python - 如何正确排序 Python 字典中的项目?

arrays - 我如何在字典中嵌套数组?

c++ - 在 Xcode C++ 项目中链接外部库

c++ - 从 c/c++ 或 linux 发布到 facebook 墙上

c++ - 如何防止时间戳被重新排序?

python - 时间作为 Python 字典的关键

python:动态获取字典中的子字典?