我是C ++的初学者,刚开始学习矢量。
有人可以建议我采用更好的方法来获取向量的值吗?或者这种方法足够好吗?提前致谢:')
vector<int> vec;
int temp;
bool condition=true;
while(condition){
cin >> temp;
vec.push_back(temp);
if(cin.get()=='\n') condition = false;
}
答案 0 :(得分:0)
更多C ++方法可能是使用std::getline
将行读入std::string
。然后将该字符串放入std::istringstream
,然后使用std::istream_iterator
填充vector。
也许像
// Somewhere to put the text we read
std::string line;
// Read the actual text
std::getline(std::cin, line);
// A stream to parse the integers from
std::istringstream iss(line);
// Define the vector, initializing it from stream iterators
// This is a more succinct version of a loop which extracts (with `>>`)
// integers and pushes them into the vector
std::vector<int> vec(std::istream_iterator<int>(iss), std::istream_iterator<int>());
此后vec
填充了来自单行输入的整数。
答案 1 :(得分:-1)
可能您可以使用C ++流函数来检查输入流是否足以从
输入。while(cin.good())
{
int i;
cin >> i;
vec.push_back(i);
}
就是这样!