问题
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;
}
i think the size() did not change the value of num, but why it cause error when complie it? it's ok when i removed the keyword const in the example function.
回答1:
The problem isn't the call to size()
. The problem is using operator[]()
on a const
map: if the key doesn't exist, the subscript operator would insert the key and, hence, modify the map. To do so, the std::map<std::string, std::vector<int>>
can't be const
, of course.
If you just want to access the values you'll need to use find()
directly:
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";
}
}
... or you can use at()
which will throw an exception when accessing a key which isn't present on a non-const
map (thanks to bamboon for pointing at this question):
void example(std::map<std::string, std::vector<int>> const& num) {
std::cout << num["A"].size() << '\n';
}
回答2:
The problem is that operator [] is not defined for const objects of type std::map. Here are declarations of the operator
T& operator[](const key_type& x);
T& operator[](key_type&& x);
As you see the qualifier const after the closing parenthesis of the parameter list is absent. However member function at is defined for const objects (see the second declaration)
T& at(const key_type& x);
const T& at(const key_type& x) const;.
So instead of the subscript operator you must use member function at.
回答3:
The function num
doesn't know that there is a key "A"
already added in another function and, if there weren't one, num["A"]
would add it. Therefore, to use []
, the map operand cannot be const
.
In short, it's not size()
's fault.
回答4:
Others pointed out what's the problem. What you could do now is e.g.
void example(const map<string, vector<int> > & num)
{
cout << num.at("A").size() << endl;
}
which would be a little bit slower.
来源:https://stackoverflow.com/questions/20814909/call-size-of-const-mapstring-vectorint-cause-error