<分区>
在处理一个很难在这里整体描述/解释的问题时遇到,所以这里是问题的相关重现。
在 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 显示出这种行为呢?