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

Rearranging numbers in array using pointers

本文关键字:数组 数字 排列 指针 新排列      更新时间:2023-10-16

我尝试使用指针重新排列数组中的数字,我实际上已经实现了它,但我最终得到了一个看起来很糟糕的代码,我知道可能有更好的方法可以做到这一点,但我无法弄清楚。我只希望您对我的代码输入。 我也知道我的整数名称不是最好的,所以请不要因此而评判我。

#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::array

然后,您可以像这样声明数组

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

避免在一行上多次声明

它使代码更难阅读,并且很容易错过变量声明,我更喜欢以下内容:

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

填充数组STL 在这里很方便,您可以使用 std::generate 它接受一系列迭代器和回调,对于范围内的每个值,它将调用函数并将返回分配给该值。使其成为与 lambda 的完美使用。

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

你应该使用 C++11 随机而不是 rand();

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

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

容易!现在我们知道数组的大小,函数更容易调用:

print(hello);

对于循环真棒!远程循环更棒!!

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

请注意,using namespace std被认为是不好的做法,一个简单的谷歌搜索会告诉你为什么。

交换

无需创建函数,可以再次使用 stl 算法,std::reverse,它会反转值给出的顺序

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