ファイルから数値を読み込み、すべての数値の平均をとってみようとしていますが、data.resize()とdata.reserve()の部分をmyコード。私はサイズ変更と予約を使用する必要があります。 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] << " ";
}
}
なぜここで '予約'を使用するのですか?そしてその点で、なぜベクターを使うのですか?一連の数値を取って平均を求めるには、1.アキュムレータと、2.カウンターが必要です。 – WhozCraig
リザーブではなく、サイズ変更が必要です。予備はサイズ変更されないので、データ[I]はあなたが押すまで無効です。あなたがする必要があるのは、resizeを呼び出してから、push_backで行を削除することです。 – Robinson
私は既に関数のサイズ変更を実装していますが、これは別の関数です。 max_sizeを特定の値に設定していますか?しかし、ファイルにいくつの値が入っているのか分からないので、私はできないと思います。 – bellaxnov