如果事先不知道会有多少物体,请使用矢量。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> a;
int entry;
cin>>entry;
// Oh, yeah. This. You really, *really* want to check `cin`.
// Otherwise, if the user decided to type "i like cheese", you'd loop
// forever getting zeros while cin tried to parse a number.
// With the array, that'd typically cause a segfault near instantly.
// With a vector, it'll just eat up all your CPU and memory. :P
while (cin && entry != 42) {
a.push_back(entry);
cout << entry << "\n";
cin >> entry;
}
return 0;
}
呃......你在哪里确定你的循环在'i> 19'之前终止,因此对'a [i]'的任何访问都可能出现段错误? – arne
你的意思是我应该增加数组的大小? – user2696751
@ Nbr44,直到一个数字是42,而不是42个元素。仍然... – chris