【发布时间】:2016-09-21 13:51:56
【问题描述】:
我正在尝试从文件中读取数字并取所有数字的平均值,但我不确定如何将 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. 一个计数器。 -
您需要调整大小,而不是保留。 Reserve 不会调整大小,因此 data[I] 在您推送之前无效。您需要做的是调用 resize 然后删除带有 push_back 的行。
-
我已经实现了一个函数resize,这是我必须编写的另一个函数。我是否将 max_size 设置为某个值?但我不认为我可以,因为我不知道文件中有多少个值。
-
我回滚了你的编辑,因为它把问题变成了完全不同的东西。问一个新问题。
标签: c++ algorithm data-structures