2015-10-18 36 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