gpt4 book ai didi

c++ - 删除 C++ 中 vector 的 const 限定符

转载 作者:行者123 更新时间:2023-12-02 01:45:05 24 4
gpt4 key购买 nike

是否可以消除 vector 的常量性?如果可以,如何实现?由于某种原因,我无法访问 main () ,我还能删除 arr 的常量吗?在下面的代码中进行狙击?感觉就是这样auto arr0 = const_cast<vector<int> & > (arr);vector<int> arr0 = arr; 相同。我想这只是显式与隐式转换的一个例子,它们都创建了原始数组“arr”的拷贝。是否可以在不创建拷贝的情况下就地删除常量?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


vector<int> func(const vector<int>& arr){
// vector<int> arr0 = arr;
auto arr0 = const_cast<vector<int> & > (arr);
sort(arr0.begin(), arr0.end());
return arr0;
}

int main(){
const vector<int> arr = {3,4,1,5,2};
auto res = func(arr);
for (auto n:res)
cout<<n<<" ";
return 0;

}

最佳答案

不要试图抛弃常量。修改 const 对象将导致未定义的行为。

It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;

实际上是一样的。 Actor 阵容是多余的。

Is it possible to remove constness inplace without creating a copy?

如果您希望在不复制的情况下对 vector 进行排序,那么首先不要将 vector 设置为常量。如果它是const,那么你不能修改它。

then what is the point of have const_cast in c++?

很少需要它,但有一些用例。

您可以使用它将非常量泛左值表达式转换为常量表达式:

void fun(T&);       // overload 1
void fun(const T&); // overload 2
T t;
fun(t); // calls 1
fun(const_cast<const T&>(t)); // calls 2

如果您有一个可证明的非常量对象,以及一个引用该非常量对象的常量引用,那么您可以放弃该引用的常量性:

T t;
const T& ref = t;
const_cast<T&>(ref) = new_value;

同样的情况也适用于 volatile 限定符,尽管这种情况很少需要。

关于c++ - 删除 C++ 中 vector 的 const 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71004397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com