函数获取一个数组作为输入

function which gets an array as an input

本文关键字:数组 输入 一个 获取 函数      更新时间:2023-10-16

我想做一个函数,它得到一个数组(array1)与大小(size1)作为输入,然后在主调用它。直到现在我才到达这一点,但是程序出了问题。有人能帮我吗?

#include <iostream>
using namespace std;
void getdata( int array1[],int size1 ) {
    cin>>size1;
    for ( int i=0; i<size1; i++) {
        cin>>array1[i];
    }
}
int main () {
    int size1;
    int array1[size1];
    getdata(array1,size1);
    return 0;
}

这里有很多错误。

  1. 你定义你的大小就像简单的int size1;。它具有未定义的值,即随机值。

  2. 使用int array1[size1],您只需创建一个随机大小的数组。

  3. 将size1传递给函数getdata,忽略变量的值,用用户的输入覆盖它。

  4. 接下来,迭代一个未知大小的数组,假设用户已经猜到了数组的大小…

那么,如何解决这个问题呢?首先,如果在编译时(在编写程序时)不知道数组的大小,则需要动态数组。您应该使用标准库中的向量类。那么,我们试试:

#include <iostream>
#include <vector>
std::vector<int> getdata() {
    int size;
    std::cout << "Vector size: ";
    std::cin >> size;
    std::cout << "Please, enter exactly " << size  << " integersn";
    std::vector<int> data(size);
    for (int i = 0; i < size && std::cin; ++i) 
        std::cin >> data[i];
    return data;
}
int main () {
    std::vector<int> data = getdata();
    std::cout << "You've inputed:";
    for (int i = 0; i < data.size(); ++i)
        std::cout << " " << data[i];
    std::cout << "nThanks, and bye!n";
    return 0;
}   

<标题> 更新

好的,我们试试没有向量。但是向我保证,你不会在产品代码中使用它,并且会很快忘记它,因为你已经学会了向量))。

我想提请您注意我是如何将大小传递给getdata函数的。我用的是参考资料。这意味着可以修改size变量的值,并且调用者可以看到修改。因此,getdata有两个输出参数(零输入)。也许更简洁的解决方案是返回一个结构体,包含一个指针和一个大小。

#include <iostream>
int *getdata(int &size) {
    std::cout << "Array size: ";
    std::cin >> size;
    std::cout << "Please, enter exactly " << size  << " integersn";
    int *data = new int[size];
    for (int i = 0; i < size && std::cin; ++i) 
        std::cin >> data[i];
    return data;
}
int main () {
    int size = 0;
    int *data = getdata(size);
    std::cout << "You've inputed:";
    for (int i = 0; i < size; ++i)
        std::cout << " " << data[i];
    std::cout << "nThanks, and bye!n";
    // now we're responsible to free the memory
    delete[] data;
    return 0;
}   

应该可以。请注意代码中的注释

#include <iostream>
using namespace std;
int* getdata(int& size) {
    // Read the size of the array.
    cin>>size;
    // Allocate memory for the array.
    int* array = new int[size];
    // Read the data of the array.
    for ( int i=0; i<size; i++) {
        cin>>array[i];
    }
    // Return the data.
    return array;
}
int main () {
    int size;
    // Get the data.
    int* array = getdata(size);
    // Use the data.
    //
    // delete the data
    delete [] array;
    return 0;
}

c++不允许可变长度数组,数组大小必须是常量表达式。
这个语句是错误的:

int size1;
int array1[size1];

如果需要,使用vectors或在heap上分配数组

And in:

void getdata( int array1[],int size1 ) {
cin>>size1;

您正在覆盖size1包含的内容。