如何确定C++中向量的值个数? 我试图用C++构建一个小任务,我需要让用户预先确定他们想要在GrassPayCuffsSvector向量中放置多少个GoffsPayPayChest.

如何确定C++中向量的值个数? 我试图用C++构建一个小任务,我需要让用户预先确定他们想要在GrassPayCuffsSvector向量中放置多少个GoffsPayPayChest.,c++,c++11,vector,cin,C++,C++11,Vector,Cin,到目前为止,这就是我所拥有的: vector<double> gross_paychecks_vector (5); double gross_paychecks; // Add 5 doubles to vector cout << "Please enter an integer" << endl; cin >> gross_paychecks; for(gross_paychecks = 0; gross_paycheck

到目前为止,这就是我所拥有的:

vector<double> gross_paychecks_vector (5);
  double gross_paychecks;
  // Add 5 doubles to vector
  cout << "Please enter an integer" << endl;
  cin >> gross_paychecks;
  for(gross_paychecks = 0; gross_paychecks <= gross_paychecks_vector; ++gross_paychecks ){
    cin >> gross_paychecks;
  }
现在我有点不知所措,因为我不确定是否要将向量切换到类似向量gross_paychecks{}的东西,因为它在for循环中抛出了一个错误


另外,我不确定如何使用for循环,我应该使用for循环还是其他什么?。我需要接受用户的输入,只要它没有达到他/她指定的总工资支票数。

您可能需要:

vector<double> gross_paychecks_vector;   // initially the vector is empty
...
  cout << "How many paychecks:" << endl;
  cin >> gross_paychecks;

  for (int i = 0; i < gross_paychecks; i++)
  {
    double value;
    cin >> value;
    gross_paychecks_vector.push_back(value);  // add new value to vector
  }

  // display values in vector
  for (auto & value : gross_paychecks_vector)
  {
     cout << value << "\n";
  }

另外。如果您想使用现代C++特性,您将使用:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

int main()
{
    std::vector<double> grossPaychecks{};

    std::cout << "How many paychecks:\n";
    size_t numberOfPaychecks{0};
    std::cin >> numberOfPaychecks;

    // Read all data
    std::copy_n(std::istream_iterator<double>(std::cin),numberOfPaychecks, std::back_inserter(grossPaychecks));

    // Print all data
    std::copy(grossPaychecks.begin(), grossPaychecks.end(), std::ostream_iterator<double>(std::cout,"\n"));

    return 0;
}