My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code:
#include <vector>
int main() {
std::vector <const int> v;
}
will not compile – you can’t create a vector of const ints. Obviously, I should have known this (and intellectually I did), but I’ve never needed to create such a thing before. However, it seems like a useful construct to me, and I wonder if there is any way round this problem – I want to add things to a vector (or whatever), but they should not be changed once added.
There’s probably some embarrassingly simple solution to this, but it’s something I’d never considered before.
I probably should not have mentioned sorting (I may ask another question about that, see this for the difficulties of asking questions). My real base use case is something like this:
vector <const int> v; // ok (i.e. I want it to be OK)
v.push_back( 42 ); // ok
int n = v[0]; // ok
v[0] = 1; // not allowed
Well, in C++0x you can…
In C++03, there is a paragraph 23.1[lib.containers.requirements]/3, which says
This is what’s currently preventing you from using
const intas a type argument tostd::vector.However, in C++0x, this paragraph is missing, instead,
Tis required to beDestructibleand additional requirements onTare specified per-expression, e.g.v = uonstd::vectoris only valid ifTisMoveConstructibleandMoveAssignable.If I interpret those requirements correctly, it should be possible to instantiate
std::vector<const int>, you’ll just be missing some of its functionality (which I guess is what you wanted). You can fill it by passing a pair of iterators to the constructor. I thinkemplace_back()should work as well, though I failed to find explicit requirements onTfor it.You still won’t be able to sort the vector in-place though.