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时,它是正常的。
发布于 2013-12-28 21:10:38
问题不在于对size()的调用。问题是在const映射上使用operator[]():如果键不存在,下标操作符将插入键,从而修改映射。要做到这一点,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映射中的键时抛出异常(感谢this指出的问题):
void example(std::map<std::string, std::vector<int>> const& num) {
std::cout << num["A"].size() << '\n';
}发布于 2013-12-28 21:40:01
问题是没有为std::map类型的const对象定义运算符[]。下面是运算符的声明
T& operator[](const key_type& x);
T& operator[](key_type&& x);正如您看到的,参数列表的闭括号后的限定符const是缺失的。然而,成员函数at是为const对象定义的(参见第二个声明)。
T& at(const key_type& x);
const T& at(const key_type& x) const;.因此,您必须使用成员函数,而不是下标运算符。
发布于 2013-12-28 21:30:28
函数num不知道已经在另一个函数中添加了一个键"A",如果没有,num["A"]会添加它。因此,要使用[],映射操作数不能为const。
简而言之,这不是size()的错。
https://stackoverflow.com/questions/20814909
复制相似问题