我试图读取文件中的数字并取所有数字的平均值,但我不确定如何将data.resize()和data.reserve()部分包含到我的码。我必须使用调整大小和保留。当我将current_size或max_size设置为data.size()为0.是否有另一种方法来查找矢量的大小?查找矢量的大小
// 1) Read in the size of the data to be read (use type size_t)
// 2) Use data.resize() to set the current size of the vector
// 3) Use a for loop to read in the specified number of values,
// storing them into the vector using a subscript
void readWithResize(vector<int> &data) {
cout << "Using resize!" << endl;
if (cin){
size_t current_size;
current_size = data.size();
//cin >> current_size;
cout << "current_size = " << current_size << endl;
data.resize(current_size);
for (size_t i = 0; i < current_size; i++){
cin >> data[i];
data.push_back(data[i]);
cout << data[i] << " ";
cout << current_size << endl;
}
}
// 1) Read in the size of the data to be read (use type size_t)
// 2) Use data.reserve() to set the maximum size of the vector
// 3) Use a for loop to read in the specified number of values,
// storing them into the vector using data.push_back()
void reserve(vector<int> &data) {
cout << "Using reserve!" << endl;
if (cin){
size_t max_size;
//max_size = 12;
data.reserve(max_size);
cout << "max_size = " << max_size << endl;
for (size_t i = 0; i < max_size; i++){
cin >> data[i];
data.push_back(data[i]);
cout << data[i] << " ";
}
}
为什么要在这里首先使用'reserve'。就此而言,为什么要使用矢量呢?要获得一系列数字并找到他们的平均值,您需要1.累加器和2.计数器。 – WhozCraig
您需要调整大小,而不是保留。保留区不会调整大小,因此数据[I]在您推送前无效。你需要做的是调用调整大小,然后用push_back删除行。 – Robinson
我已经实现了一个函数调整大小,这是我必须编写的另一个函数。我是否将max_size设置为某个值?但我不认为我可以,因为我不知道文件中有多少个值。 – bellaxnov