2017-06-22 61 views
0

我已經嘗試使用指針重新排列數組中的數字,但我實際上已經實現了它,但是我以一個可怕的代碼結束了,我知道可能有更好的方法來做到這一點,弄明白了。我只想在我的代碼上輸入內容。 另外我知道我的整數的名字不是最好的,所以請不要評論我。使用指針重新排列數組中的數字

#include <iostream> 
using namespace std; 
void Fill(int a[], int b) { 
    for (int i = 0; i < b; i++) 
        *(a + i) = rand() % 100; 
} 
void Print(int a[], int b) { 
    for (int i = 0; i < b; i++) 
        cout << *(a + i) << " "; 
} 
void swap(int a[], int b, int c[]) { 
    for (int i = 0; i < b; i++) { 
        *(c + (b - i - 1)) = *(a + i); 
    } 
    for (int i = 0; i < b; i++) { 
        *(a + i) = *(c + i); 
    } 
    for (int i = 0; i < b; i++) { 
        cout << *(a + i) << " "; 
    } 
} 
int main() { 
    int hello1[10], goodbye[10]; 
    Fill(hello1, 10); 
    Print(hello1, 10); 
    cout << endl; 
    swap(hello1, 10, goodbye); 
    cin.get(); 
    cin.get(); 
    return 0; 
} 
+3

你爲什麼不只是使用指數,這是同樣的事情更短的形式! –

回答

1

對於固定大小的數組喜歡的std ::陣列

然後,您可以聲明數組這樣

std::array<int, 10> hello, goodbye; 

避免在一行多個聲明

它使代碼更難閱讀,很容易錯過變量聲明I prefere如下:

std::array<int, 10> hello; 
std::array<int, 10> goodbye; 

填充陣列 的STL得到方便在這裏,你可以使用std ::產生,這需要一系列的迭代器和回調,對範圍內的每個值就會調用函數並將返回值分配給該值。與lambda完美搭配使用。

std::generate(hello.begin(), hello.end(), []{return rand() % 100;}); 

而且你應該使用C++ 11 random而不是rand();

打印 首先,讓我們來看看如何通過我們的陣列,因爲陣列的類型取決於它的大小,我們必須使用一個模板函數

template<size_t size> 
void print(const std::array<int, size>& array) 
{ 
} 

輕鬆!現在我們知道陣列的大小和功能更容易調用:

print(hello); 

For循環是真棒!遠程循環更加棒!

for(int value : hello) 
    std::cout << value << ' '; 

請注意,using namespace std被認爲是不好的做法,一個簡單的谷歌搜索會告訴你爲什麼。

交換

無需創建一個功能,您可以再次使用STL算法,性病::扭轉,這將扭轉的價值序列給

std::reverse(hello.begin(), hello.end()); 

和打印您陣列再次

print(hello); 

而且你不需要再見了

結論

最後,它是所有關於知道哪些工具可用來你

#include <iostream> 
#include <array> 
#include <algorithm> 

template<size_t size> 
void print(const std::array<int, size>& array) 
{ 
    for(int value : hello) 
     std::cout << value << ' '; 

    std::cout << '\n'; 
} 

int main() 
{ 
    std::array<int, 10> hello; 
    std::generate(hello.begin(), hello.end(), []{return rand() % 100;}); 

    print(hello); 
    std::reverse(hello.begin(), hello.end()); 
    print(hello); 
}