[我正在尝试使用C ++构建一个小任务,在该任务中,我需要允许用户预先确定要在名为'gross_paychecks_vector'的向量中放置多少Gross_paychecks。
到目前为止,这就是我所拥有的:
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;
}
现在,我有点迷失了,因为我不确定是否将向量切换到vector<double> gross_paychecks {}
之类,因为它会在for循环中引发错误。
另外,我不确定如何使用for循环(我是否应该实际使用for循环或其他方法?)。我需要接受来自用户的输入,只要它不符合他/她指定的gross_paychecks数量即可。
您可能想要这个:
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;
}