Can I legally write to the data pointed to by a co

2020-07-27 04:34发布

问题:

I have a constant integer vector const vector<int> v = {5,1,3,2,4} . How can I sort it without using any extra memory like vector, array etc.

回答1:

You can't.

Your vector is immutable. It cannot be changed. There is no [legal] way to re-order its contents.

By extension, if you want a sorted version of its contents, you will need a new vector, which needs more memory.



回答2:

As you have shown in your answer the solution is to cast away const from the vector, ie:

vector<int>&temp = const_cast<vector<int>&>(v);
sort(temp.begin(), temp.end());

This works because you are not changing the state of the vector. The only thing standard says about undefined behavior and casting away const is in [dcl.type.cv]/4

Any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior. [...]

Any nothing in [expr.ass], [expr.post.incr], and [expr.pre.incr] applies to this example so you are not considered to be modifying the object.


I do feel this is a defect though. The order of the elements matter for comparison operators so this modification should apply.



回答3:

I have tested using c++11. In my job, it's working fine for me

You can sort any constant container in c++ using a pointer.

In your case, if you want to sort this vector using sort(v.begin(),v.end()) then it will result in some runtime error due to violation of const.

But you can sort your container in following way-

vector<int>*temp=(vector<int>*)&v;
sort(temp->begin(),temp->end());

After this, your constant vector v will be like this -

const vector<int> v = {1,2,3,4,5}