C ++ | use const std :: map, map encountered a bug :: [] when

After primitive simplified as follows:

void fun(const map<int,vector<int>> &mp, int index) {
    for (auto tmp : mp[index]) {
        //......
    }
}

The results given as follows:

[Error] passing 'const std::map<int, std::vector<int> >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = std::vector<int>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::vector<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector<int>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive]

After a long inquiry that is probably out of the question, for the use of non-const objects const member functions: std :: map :: [] itself is not const member functions (operator), for not map a keyword, use subscript operator creates a new entry, change the map.

Solutions are available as follows:

  • Remove const, so there is a certain security risk
  • Copy of the map, there are some performance overhead
  • For C ++ 11, you can use the Map :: AT . It has const and non-const two versions, the case did not match keyword, throws out_of_range. Since the subscript checking, it also brings a performance penalty.

Conclusion: Many const member functions are set and non-const two versions, in such a situation to play its meaning. It should also be noted that small differences between the same or similar functions when the function for future use.

Guess you like

Origin www.cnblogs.com/wyzersblog/p/11374046.html
Recommended