Reputation: 139
My example code is
class A
{
int a = 0;
public:
void setA(const int value)
{
a = value;
}
};
std::map<std::string, std::set<A>> Map{{"A", {}}};
Map.rbegin()->second.rbegin()->setA(2);
I get the following error: "Member function 'setA' not viable: 'this' argument has type 'const A', but function is not marked const"
My question is why rbegin() returns a const pointer to A? Or why is the std:pair's second a const in the std::map?
Upvotes: 0
Views: 952
Reputation: 17483
Basically, rbegin()
returns a reverse iterator which points to an object of type A
which is stored in the std::set
in a const manner.
The reason behind such behaviour is quite simple: it is necessary to protect std::set
from inadvertent changes of elements which are stored inside.
You should remember, that std::set
stores its elements in a tree-like data structure to ensure fast search/insert/remove operations. Possible changes of elements inside std::set
might lead to wrong elements comparison and corruption of data structure, that is why all iterators return by begin()
/end()
methods and their analogues expose elements in a const fashion.
Upvotes: 2
Reputation: 385204
All std::set
elements are exposed in const
fashion. That's because they're both keys and values, and if you could modify keys willy-nilly then you'd ruin the tree structure inside the set.
It is currently not possible to directly modify set elements. You will have to remove then re-insert.
(This has nothing to do with the encapsulating map.)
Upvotes: 3