我的目标是采用 3 个标准整数数组并使用 vector 方法来操作它们,而不必将所有数组元素复制到单独的 vector 数组中。
我想在不复制数组元素的情况下执行此操作的原因是,这些数组将非常大,效率是首要任务。
这里有两个我希望它看起来像的例子:
- 最简单的例子:
int arr[10000];
int *ptr;
std::vector<int> & v = ptr;
v.push_back(10);
- 函数示例:
// Function that inputs 3 integer arrays and creates pointers to them.
void use_vector(int *dst, int *src1, int *src2) {
//creates vector references (without copying the original array elements)
std::vector<int> & v_dst = dst;
std::vector<int> & v_src1 = src1;
std::vector<int> & v_src2 = src2;
// do something using vector methods:
v_dst.push_back( v_scr1.size() + v_scr2.size() );
}
在这两种情况下,我都会收到此错误消息:
error: invalid initialization of reference of type ‘std::vector<int>&’ from expression of type ‘int*’
std::vector<int> &v = ptr;
理想情况下, vector 是引用 (std::vector &),但如果引用不可能,它们也可以是指针 (std::vector *)。
最佳答案
你不能这样做,因为 std::vector
在设计时对其所持有的数据具有所有权语义。
这意味着它不是设计用来包装值数组并存储它的。它必须拥有数据,因此需要一个拷贝(或从另一个 std::vector
移动)。
关于c++ - 创建对整数数组指针的 vector<int> 引用 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566162/