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

标签 c++ arrays pointers

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

#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 random 而不是 rand();

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

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

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

print(hello);

For 循环很棒!范围 for 循环更棒!!

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

请注意,using namespace std 被认为是不好的做法,简单的 google 搜索就会告诉您原因。

交换

不需要创建一个函数,你可以再次使用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);
}

关于c++ - 使用指针重新排列数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44708487/

相关文章:

c++ - 从 C++ 中的字符串中删除空格

c++ - 类模板中的转换运算符

php - 如何更改数组键以从 1 而不是 0 开始

php - 动态访问 PHP 数组

javascript - 在数组中选择数组中的值; JavaScript

C 指针错误,得到 exc_bad_access code=2,address0x100000000

c++ - 如果页面是从 Qt RCC 资源系统加载的,QWebEngineView 不会从 html 页面加载相关资源

C++ MinGW 链接器错误 _ZNSt7__cxx1112basic_stringlcSt11char_traitslcESalcEE10_M_replaceEjjPKcj

在 C 中即时更改标准输出(putch() 函数)

C++ 将指针传递给多维数组