函数获取一个数组作为输入
function which gets an array as an input
我想做一个函数,它得到一个数组(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;
}
这里有很多错误。
-
你定义你的大小就像简单的
int size1;
。它具有未定义的值,即随机值。 -
使用
int array1[size1]
,您只需创建一个随机大小的数组。 -
将size1传递给函数
getdata
,忽略变量的值,用用户的输入覆盖它。 -
接下来,迭代一个未知大小的数组,假设用户已经猜到了数组的大小…
那么,如何解决这个问题呢?首先,如果在编译时(在编写程序时)不知道数组的大小,则需要动态数组。您应该使用标准库中的向量类。那么,我们试试:
#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
包含的内容。
相关文章:
- 检查TCHAR数组输入是否为带符号整数C++
- C++数组输入不接受一定数量的整数
- 为什么我的代码无法处理大型数组输入(>10000)?
- 我正在努力处理多维数组输入和输出,我管理输入,但是打印无法按计划工作
- 使用无符号字符数组输入十六进制数
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 如何从用户获取数组输入
- C 2x2数组输入线
- 字符数组输入限制
- 将字符串数组输入到函数C++
- C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题
- 数组排序、数组输入、数组输出
- 将字符数组输入stdin
- 如何在 c++ 中为对象数组输入字符串
- 如何在c++ mex文件中访问多维数组输入
- 读取文件并将其作为整型数组输入
- 从c++文件中获取输入(矩阵数组输入)
- 数组输入不工作
- 函数结构数组输入cin问题
- 结束数组输入(c++行业标准)