2016-09-21 5 views
-3

ファイルから数値を読み込み、すべての数値の平均をとってみようとしていますが、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

なぜここで '予約'を使用するのですか?そしてその点で、なぜベクターを使うのですか?一連の数値を取って平均を求めるには、1.アキュムレータと、2.カウンターが必要です。 – WhozCraig

+1

リザーブではなく、サイズ変更が必要です。予備はサイズ変更されないので、データ[I]はあなたが押すまで無効です。あなたがする必要があるのは、resizeを呼び出してから、push_backで行を削除することです。 – Robinson

+0

私は既に関数のサイズ変更を実装していますが、これは別の関数です。 max_sizeを特定の値に設定していますか?しかし、ファイルにいくつの値が入っているのか分からないので、私はできないと思います。 – bellaxnov

答えて

2

resizereserveを気にしないでください。値をタイプintのローカル変数に読み込み、data.push_back()を使用してベクターに追加します。ベクトルは必要に応じてサイズ変更されます:

int value; 
while (std::cin >> value) 
    data.push_back(value); 

これは、入力値の任意の数を正しく処理します。しかし、@WhozCraigのコメントを見てください。

+0

「サイズ変更」と「予約」を使用する方法はありますか? – bellaxnov

+0

@bellaxnov - あなたが最終的にいくつの要素を知っている場合にのみ。このコードでは、実際にはどちらか一方が必要ありません。 –

+0

もし私がそれらを使用するなら、どのように多くの要素があるのでしょうか? – bellaxnov

関連する問題