首页 文章

为什么const不适用于stl map的size(),而它适用于其他容器? [重复]

提问于
浏览
1

这个问题在这里已有答案:

在处理一个难以在整体上解释/解释的问题时遇到,所以这里是问题的相关重构 .

用windows上的gnu g编译这段代码

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

给出以下神秘错误

在函数'int recreate(const std :: map >> &&)'中:D:\ _mpoo \ testit.cpp:12:21:错误:将'const std :: map >>>作为'this'参数传递给' 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]'丢弃限定符[-fpermissive] cout <

而从重新创建函数中删除const后,它运行良好,即

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

在我的理解中,当值保持不变时,我们使用const来指示编译器进行一些优化 . 现在,对象上使用的size()函数在每次执行时都会改变某些值,或者某些内存被分配给调用size()时映射容器 .

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

2 回答

  • 6

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

    然后你尝试在那个位置的 vector<string> 上调用 size() ,但到目前为止已经太晚了 . 顺便提一下,size() is const在标准库容器上 .

  • 4

    它实际上不是 size ,它是非常量的operator[] .

    返回对映射到等效于key的键的值的引用,如果此键尚不存在则执行插入 .

相关问题