2017-06-22 20 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); 
}