C++ 使用指针重新排列数组中的数字

C++ 使用指针重新排列数组中的数字,c++,arrays,pointers,C++,Arrays,Pointers,我曾经尝试过用指针在数组中重新排列数字,我实际上已经做到了,但我最终得到了一个看起来很糟糕的代码,我知道可能有更好的方法来实现这一点,但我想不出来。我只想让你输入我的代码。 而且我知道我的整数的名字不是最好的,所以请不要因为这个来评判我 #include <iostream> using namespace std; void Fill(int a[], int b) {     for (int i = 0; i < b; i++)         *(a + i) = ra

我曾经尝试过用指针在数组中重新排列数字,我实际上已经做到了,但我最终得到了一个看起来很糟糕的代码,我知道可能有更好的方法来实现这一点,但我想不出来。我只想让你输入我的代码。 而且我知道我的整数的名字不是最好的,所以请不要因为这个来评判我

#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;
}
#包括
使用名称空间std;
填空(整数a[],整数b){
对于(int i=0;icout对于固定大小的数组,首选std::array

然后可以像这样声明数组

std::array<int, 10> hello, goodbye;
您应该使用C++11 random而不是rand()

打印 首先让我们看看如何传递数组,因为数组的类型取决于它的大小,所以我们必须使用模板函数

template<size_t size>
void print(const std::array<int, size>& array)
{
}
对于循环是可怕的!范围为循环更可怕

for(int value : hello)
    std::cout << value << ' ';
然后再次打印阵列

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);
}
#包括
#包括
#包括
模板
无效打印(常量标准::数组和数组)
{
for(int值:hello)

你为什么不直接使用索引呢?索引是同一事物的一种更短的形式!
for(int value : hello)
    std::cout << value << ' ';
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);
}