Possible Duplicate:
Why does stack<const string> not compile in g++?
We know that vector<const int>
is not allowed.
But is map<const int, int>
, map<int, const int>
, or map<const int, const int>
allowed?
Why (not)?
Possible Duplicate:
Why does stack<const string> not compile in g++?
We know that vector<const int>
is not allowed.
But is map<const int, int>
, map<int, const int>
, or map<const int, const int>
allowed?
Why (not)?
Items in a vector must be copy-constructible or (as of C++11) move-constructible.
The key in a map only needs to be destructible, not copy/move constructible, so the requirements are much looser in this respect.
As to why that is, it's pretty simple: when/if a vector gets resized, the data from the existing buffer must be copied or moved into the new buffer. By contrast, a map normally stores its contents as nodes in a tree. Once a node is created, it will simply exist until it is destroyed. While the tree does need balancing at times, that only requires manipulating pointers between the nodes -- the key in the node is never modified after the node is created.
You'll need to be able to insert copies for the items stored in STL containers, that's why it's not allowed.
You may still use const references to export containers for read only access via a const_iterator
from a class method (getter).