使用指针重新排列数组中的数字
Rearranging numbers in array using 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 随机而不是 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);
}
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 是否可以将数组数字作为函数来执行?