c++ - 为什么 const 不能与 STL 映射的 size() 一起使用,而它可以完美地用于其他容器?

标签 c++ vector stl constants

<分区>

在处理一个很难在这里整体描述/解释的问题时遇到,所以这里是问题的相关重现。

在 Windows 上使用 gnu g++ 编译这段代码

int recreate(const map <int , vector<string> > &bitFieldMap){
    cout<<bitFieldMap[1].size();
}
int main(){}

给出以下神秘错误

In function 'int recreate(const std::map > >&)': D:\playground\testit.cpp:12:21: error: passing 'const std::map > >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = int; _Tp = std::vector >; _Compare = std::less; _Alloc = std::allocator > > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector >; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive] cout<

而在从 recreate 函数中删除 const 后,它运行良好,即

int recreate( map <int , vector< string > > &bitFieldMap){
    cout<< bitFieldMap[1].size() ;
}
int main(){}

根据我的理解,当值保持不变时,我们使用 const 来通知编译器进行一些优化。现在对象上使用的 size() 函数每次执行时都会更改一些值,或者在调用 size() 时分配给映射容器的一些内存发生了一些奇怪的事情。

现在我的问题可以通过不在这里使用 const 或使用 multimap 来解决。但是为什么 const 和 size 显示出这种行为呢?

最佳答案

您没有调用 size()map 上.你是calling operator[] map 上,这是一个非 const操作,因为如果一个元素尚不存在,它将在该位置创建一个元素。

然后您尝试调用 size()vector<string> 上在那个位置,但此时为时已晚。顺便说一下, size() is const 在标准库容器上。

关于c++ - 为什么 const 不能与 STL 映射的 size() 一起使用,而它可以完美地用于其他容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859741/

相关文章:

c++ - 函数调用给我错误表达式必须有类类型

C++/OpenGL : VAOs work individually but not together

vb.net - Visual Basic .net 中的数组列表

c++ - 为什么 C++ lower_bound() 允许返回等于 val 的指针而 upper_bound() 不允许

c++ - 如何为 random_shuffle 编写 range-v3 Action ?

c++ - 从逆序C++访问 vector 时发生运行时错误

c++ - 组合字符串 vector

c++ - 包含存储在 vector 中的 auto_ptr 的类

c++ - const 类型容器的 const_iterator 类型

c++ - 数组成员配对的一般公式?