首页 > 解决方案 > 如何从未知数量的 int 的行构造一个向量 // c++

问题描述

通常输入的数量是给定的,我可以用 for 循环来做,但不在那里:https ://codeforces.com/contest/469/problem/A

我拼命地尝试从一行 ints 构造一个向量,但我只知道 int 的数量不能高于 100。有 2 行输入。

如果我做了一个 Cin 的无限循环,当它到达行尾或输入端时我怎么能打破它?

标签: c++

解决方案


You might consider reading in the entire line as a string first:

std::string line;
std::getline (istream,name);

then splitting that string into your vector (boost example):

std::vector<int> split(std::string const& str)
{
    using namespace std;
    using namespace boost;
    std::vector<int> results;
    tokenizer<> tok(str);
    for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       results.emplace_back(std::stoi(*beg));
    }
    return results;
}

推荐阅读