如标题所示,是否可以在不复制且仅使用指针的情况下将多个数组连接在一起?我花费了大量的计算时间将较小的数组复制到较大的数组中。 注意我不能使用 vector ,因为 umfpack(一些矩阵求解库)不允许我使用或者我不知道如何使用。
举个例子:
int n = 5;
// dynamically allocate array with use of pointer
int *a = new int[n];
// define array pointed by *a as [1 2 3 4 5]
for(int i=0;i<n;i++) {
a[i]=i+1;
}
// pointer to array of pointers ??? --> this does not work
int *large_a = new int[4];
for(int i=0;i<4;i++) {
large_a[i] = a;
}
注意:我知道已经有一个简单的解决方案,就是将它们迭代地复制到一个新的大数组中,但很高兴知道是否不需要复制在整个持续时间内存储的重复 block 程序。我处于学习曲线 atm 中。
感谢大家阅读
最佳答案
as in the title is it possible to join a number of arrays together without copying and only using pointers?
简而言之,没有。
指针只是内存中的地址 - 就像街道地址。你不能将两栋房子并排移动,只能通过复制它们的地址来实现。您也不能通过更改地址将两所房子一起移动。更改地址不会移动房子,它指向一个新房子。
note I can't used vectors since umfpack (some matrix solving library) does not allow me to or i don't know how.
在大多数情况下,当需要数组时,您可以传递 std::vector
的第一个元素的地址。
std::vector a = {0, 1, 2}; // C++0x initialization
void c_fn_call(int*);
c_fn_call(&a[0]);
这是有效的,因为 vector
保证其内容的存储始终是连续的。
但是,当您从 vector
插入
或删除
一个元素时,它会使指针无效以及来自它的迭代器。如果它分配的存储必须改变大小,您可能从获取元素地址获得的任何指针不再指向 vector
。
关于C++:将数组连接在一起-是否可以使用指针而不进行复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6900925/