简体   繁体   中英

Reversing an array of structures in c++

I have a structure definition as below:

struct Rect {
int l;  
int b;  
int h; 
};

The input format is :

10 20 30 40 50 60 12 2 3 
10 2  4  44 50 887 12 3 3

I have successfully implemented the program to take in the input and store in an array of Rect structures.

Now I am trying to implement a function to reverse the input and output as below:

12 2 3 40 50 60 10 20 30
12 3 3 44 50 887 10 2 4 

I have tried implementing my own reverse function and use it but it didnt work, the below is my reverse function:

void reverseArray(Rect *arr, int start, int end)
{
    Rect *temp;
    while(start < end)
    {
        temp = &arr[start];
        arr[start] = arr[end];
        arr[end] = *temp;
        start++;
        end--;
    }
}

How can I achieve the desired format?, thank you.

I would simply use std::reverse

I would recommend to use std::vector instead of your arrays.

Live code

Rect r1{1,2,3};
Rect r2{4,5,6};
Rect r3{7,8,9};
std::vector<Rect> v = {r1, r2, r3};
std::reverse(v.begin(),v.end());

Rect arr[3] = {{1,2,3}, {4,5,6}, {7,8,9}}; // works also with arrays
std::reverse(std::begin(arr),std::end(arr));

The other answer about std::reverse is on the right track....but the correct way to use it is:

Rect* pBegin = arr + start;
Rect* pEnd = arr + end;

std::reverse(pBegin, pEnd);

Basically, std::reverse requires iterators and pointers are naturally iterators.

Rect* temp is a pointer, this means that you are holding the address of your arr[start] in your temp value. Not the value of the struct. So when you say arr[start] = arr[end] arr[start] now contains a new value. But because temp is just pointing at that location in memory *temp will now equal the new value as well. You need to make a copy of the struct into temp and not just hold a pointer. Something along the lines of:

void reverseArray(Rect arr, int start, int end)
{
    Rect temp;
    while(start < end)
    {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM