[英]Can I legally write to the data pointed to by a constant vector, e.g. sort it?
I have a constant integer vector const vector<int> v = {5,1,3,2,4}
.我有一个常数 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.如何在不使用任何额外的 memory(如向量、数组等)的情况下对其进行排序。
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.通过扩展,如果你想要其内容的排序版本,你将需要一个新的向量,它需要更多的 memory。
As you have shown in your answer the solution is to cast away const from the vector, ie:正如您在答案中所示,解决方案是从向量中丢弃 const ,即:
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.这是有效的,因为您没有更改向量的 state。 The only thing standard says about undefined behavior and casting away const is in [dcl.type.cv]/4
标准中关于未定义行为和抛弃 const 的唯一说明是在[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.
任何尝试修改 ( [expr.ass] , [expr.post.incr] , [expr.pre.incr] ) const object ( [basic.type.qualifier] ) 在其生命周期 ( [basic.life] ) 结果在未定义的行为中。 [...]
[...]
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. [expr.ass]、[expr.post.incr] 和 [expr.pre.incr] 中的任何内容都适用于此示例,因此您不会被视为正在修改 object。
I do feel this is a defect though.我确实觉得这是一个缺陷。 The order of the elements matter for comparison operators so this modification should apply.
元素的顺序对比较运算符很重要,因此应该应用此修改。
I have tested using c++11.我已经使用 c++11 进行了测试。 In my job, it's working fine for me
在我的工作中,它对我来说很好
You can sort any constant container in c++ using a pointer.您可以使用指针对 c++ 中的任何常量容器进行排序。
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
.在您的情况下,如果您想使用
sort(v.begin(),v.end())
对该向量进行排序,那么由于违反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 -在此之后,您的常量向量 v将是这样的 -
const vector<int> v = {1,2,3,4,5}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.