Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selective shallow copy from one array to another

Assuming I have 2 array of different size i.e

int arr[] = {0,1,2,3,4,5,6,7,8,9};
int *arr2 = new int[5];

I want to shallow copy some of them, Deep copy equivalent would be

int j =0;    
if(!(i%2))
    {
        arr2[j]=arr[i];
        j++;
    }

Right now a print of arr2 will output : 0, 2, 4, 6 ,8

The reason I want to shallow copy is because I want arr2 to update with any changes to arr.

That is if I loop and square all the elements in arr

I want arr2 to output : 0, 4, 16, 36 ,64

These 2 arrays are part of the same class, one is my polygonal information, and the other part is data driven. arr is actually 4000+ elements in size, and arr2 is close to 3000. At the moment my algorithm works great with deep copy. but because I need to deep copy 3000 elements per update frame, i am wasting resources and was wondering if i could somehow do this via shallow copy so I don't have to have to update arr2 every frame. The way my code needs it to work, arr actually has repeated values of arr2. arr2 is a list of points that is animated. then the data is duplicated to arr which hold the positional data for vertices. this is because arr contains multiple bezier patches, some of them share one edge or more with another patch. but i want that to be ignored when animating else there are breaks in the surface.

It is important that the copy involves indices like

arr2[j]=arr[i];

because that is how my code is setup. And that the operation be low load.

like image 790
new2code Avatar asked Jul 31 '14 04:07

new2code


1 Answers

You will need an array of integer pointers for that.

int *arr2[5];

for (int i = 0, j = 0; i < 10; i++) {
    if (!(i%2)) {
        arr2[j]= &arr[i];
        j++;
    }
}

So you need to set each element of arr2 to point to corresponding element in arr by arr2[j]= &arr[i];

When you need to access element in arr2, you call some thing like: int a = *arr2[j];

Later on let say you change arr[0] to 10 arr[0] = 10; then int a = *arr2[0]; will give you 10.

like image 58
Krypton Avatar answered Nov 02 '22 00:11

Krypton