是否可以复制
MyStruct * const * array1
自
MyStruct * array1
但只是作为一个浅层的副本?我需要对其进行排序并写回它,我也想在数组 1 中进行更改
编辑:我很愚蠢,我在 array1 上忽略了 **,然后这是有道理的。
我猜你的意思是const MyStruct * array1?
在任何情况下,您都可以使用 const_cast 来更改指针的恒常性:
const MyStruct * array1;
MyStruct * array2 = const_cast<MyStruct *>(array1);
或
const MyStruct * const array1;
MyStruct * array2 = const_cast<MyStruct *>(array1);
完全适用于问题中的结构...但是,第二个array1
替换为另一个指针parray
。
也许,即使它是结构的浅拷贝,您也将其限定为深拷贝?那么,也许,另一个答案更好。
struct MyStruct { 国际 i; int* p;};整数 j=2;MyStruct st={ 1, &j };int main() { MyStruct* parray1(&st); MyStruct* const* array1(&parray1); MyStruct * parray=new MyStruct(); parray->i = (*array1)->i; parray->p = (*array1)->p; /* 这本质上与 (*parray) = *(*array1); */ 删除阵列;}
编辑:第二个示例,如此答案的评论中所述。这里我们有一个非常量指针,我们从常量指针指针array1
连续分配指针值。
#include <iostream>
struct MyStruct {
int i;
int* p;
};
int j=2;
MyStruct st1={ 1, &j }, st2={ 2, &j };
int main() {
MyStruct* parray1[2] = {&st1, &st2};
MyStruct* const *array1(parray1);
std::cout << array1[0]->i << ' ' << array1[1]->i << 'n';
MyStruct* parray=array1[0];
parray->i = 3;
parray=array1[1];
parray->i = 4;
std::cout << array1[0]->i << ' ' << array1[1]->i << 'n';
return 0;
}
相应的输出:
1 2
3 4
在最后的评论(我认为)之后,我们对这个问题达成了共同的解释。const 数组中的指针将被复制到非 const 数组中,在那里可以重新排列它们并修改对象。
#include <iostream>
#include <algorithm>
struct MyStruct {
int i;
int* p;
};
int j=2;
MyStruct st1={ 1, &j }, st2={ 2, &j };
int main() {
MyStruct* parray1[2] = {&st1, &st2};
MyStruct* const *array1(parray1);
std::cout << array1[0]->i << ' ' << array1[1]->i << 'n';
MyStruct* parray[2];
std::copy(array1,array1+sizeof(parray)/sizeof(parray[0]),parray);
// some manipulation:
std::swap(parray[0],parray[1]);
parray[0]->i = 3;
parray[1]->i = 4;
std::cout << array1[0]->i << ' ' << array1[1]->i << 'n';
return 0;
}
新输出为:
1 2
4 3