2015-10-18 63 views
0

我有如下的结构定义的数组:倒车++结构在C

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

输入格式为:

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

我已经成功地实施程序采取在输入和存储在一个Rect结构数组中。

现在我想实现一个功能,扭转输入如下输出:

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

我试图实现我自己的逆向功能,并使用它,但它没有工作,下面是我的反转功能:

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--; 
    } 
} 

我该如何达到想要的格式?谢谢。

+4

[std :: reverse](http://www.cplusplus.com/reference/algorithm/reverse/) – 101010

回答

1

有关的std ::逆转是在正确的轨道上....但使用它的正确方法对方回答是:

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

std::reverse(pBegin, pEnd); 

基本上,STD: :反向需要迭代器,指针自然是迭代器。

+0

这假定'开始'和'结束'是零索引。 – Hawkmooon

+0

如果我确切知道输入中有多少个矩形结构,我可以使用上述解决方案吗?就像问题中的例子start = 0和end = 6那样,对吗? – Harry

+0

如何反转一行一行? – Harry

1

我会简单地使用std::reverse

我会建议使用std::vector,而不是你的阵列。

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)); 
+0

不需要使用'std :: vector''std :: reverse'也可以在常规数组上运行。 – 101010

+0

@ 101010你会如何使用它与数组,我试图给它错误,你可以举一个小例子 – Harry

+0

@哈利看到我的[live code](http://coliru.stacked-crooked.com/a/73dd751b2fbbf870) 。正如101010所说,你可以使用你的数组。 – coincoin

0

矩形* temp是指针,这意味着你在你的温度值保持您的ARR [开始]的地址。不是结构的值。所以当你说arr [start] = arr [end] arr [start]现在包含一个新的值。但是因为temp只是指向内存中的那个位置,所以temp现在也等于新的值。您需要将结构的副本制作为temp,而不是只保存一个指针。沿着线的东西:

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--; 
    } 
} 
+0

男子我不善于解释的东西。 – marsh