如何确定在 C++ 中添加到向量的值的数量?
How to determine number of values added to vector in C++?
我正在尝试使用 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 循环还是其他东西?)。我需要接受用户的输入,只要它没有达到 he/she 指定的 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;
}
我正在尝试使用 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 循环还是其他东西?)。我需要接受用户的输入,只要它没有达到 he/she 指定的 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;
}