[英]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. 我已经成功实现了该程序,以接受输入并将其存储在Rect结构的数组中。
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 我只会使用std :: reverse
I would recommend to use std::vector
instead of your arrays. 我建议使用std::vector
而不是您的数组。
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: 关于std :: reverse的另一个答案是正确的....但是使用它的正确方法是:
Rect* pBegin = arr + start;
Rect* pEnd = arr + end;
std::reverse(pBegin, pEnd);
Basically, std::reverse requires iterators and pointers are naturally iterators. 基本上,std :: reverse需要迭代器,而指针自然是迭代器。
Rect* temp is a pointer, this means that you are holding the address of your arr[start] in your temp value. Rect * temp是一个指针,这意味着您要在temp值中保留arr [start]的地址。 Not the value of the struct. 不是该结构的值。 So when you say arr[start] = arr[end] arr[start] now contains a new value. 因此,当您说arr [start] = arr [end]时arr [start]现在包含一个新值。 But because temp is just pointing at that location in memory *temp will now equal the new value as well. 但是因为temp只是指向内存中的那个位置,所以* temp现在也将等于新值。 You need to make a copy of the struct into temp and not just hold a pointer. 您需要将结构的副本复制到temp中,而不仅仅是保留一个指针。 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--;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.