有没有办法避免全局数组

Is there a way avoid a global array?

本文关键字:全局 数组 有没有      更新时间:2023-10-16

我为初学者C++类做的一项实验室作业涉及打印存储在数组中的一系列数字的平方根。程序本身是有效的,但我的老师不希望我们使用全局变量。

void assignValue(){
for (int x=0; x<10; x++){
int num;
num = rand() % 100 + 1;
if (num % 2 != 0){
num += 1;
}
arr[x] = num;
}

以下是的主要方法

int main() {
srand(static_cast<unsigned int>(time(0)));
assignValue();
for (int f = 0; f < 10; f++){
cout << f << setw(8) << right << arr[f];
float square = sqrt(arr[f]);
cout << setw(8) << right << fixed << setprecision(3) << square << endl;
}

arr是主方法之上的全局变量。

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
void assignValue(int arr[], size_t n) {
for (int i=0; i<n; ++i) {
int num;
num = std::rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
int main() {
const size_t size = 10;
int arr[size];
std::srand(static_cast<unsigned int>(std::time(0)));
assignValue(arr, size);
for (int i = 0; i < size; ++i){
std::cout << i << std::setw(8) << std::right << arr[i];
float square = std::sqrt(arr[i]);
std::cout << std::setw(8) << std::right << std::fixed << std::setprecision(3) << square << std::endl;
}
return 0;
}

以下是对采用数组引用的函数的建议:

// headers omitted (you'll need additionally iomanip, ctime, cstdlib, cmath)
// The constant is necessary because the function takes 
// a reference to an array *of this specific size*
const size_t ARR_SIZE = 10;
// Take a reference to the array (the array is not copied)
void assignValue(int (&arr)[ARR_SIZE]) 
{
for (int i = 0; i < ARR_SIZE; i++) {
int num = rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}

您可以简单地用调用函数

int main() 
{
int arr[ARR_SIZE];
// [...]
assignValue(arr);
// ...
}

以下是一种更符合核心准则的方法,因为不需要指针或大小信息。

#include <cstddef>
#include <cstdlib>
template<typename T, std::size_t N>
void assignValue(T (&arr)[N])
{
for (auto &elem : arr) {
elem = rand() % 100 + 1;
if (elem % 2 != 0) {
elem += 1;
}
}
}
auto
main() -> int
{
constexpr const auto ARRAY_SIZE = 10;
int arr[ARRAY_SIZE];
assignValue(arr);
return 0;
}