因为人们抱怨我怎么叫我的第一个答案“一个简单的拿”,这里使用Boost精神正确的版本:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
int main()
{
typedef std::vector<std::vector<double>> data_t;
typedef boost::spirit::istream_iterator It;
std::cin.unsetf(std::ios::skipws);
It first(std::cin), last;
bool ok;
data_t contents;
{
using namespace boost::spirit::qi;
static rule<It, data_t(), blank_type, locals<int>> file;
static rule<It, std::vector<double>(int number), blank_type> row;
_a_type number; // friendly alias
file %= -(omit [int_[number=_1]] > eol > row(number)) % eol;
row = repeat(_r1) [ double_ ];
ok = phrase_parse(first, last, file, blank, contents);
}
if (ok) for (auto& row : contents)
{
std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));
std::cout << "\n";
}
if (first!=last)
std::cout << "Warning: end of file not reached, remaining unparsed: '" << std::string(first, last) << "'\n";
}
这显然远远优于
- 它使用少得多包括行:)
- 需要大约10倍的编译时间(无优化),另外优化16%
- 它需要大约5年o ˚F研究的元编程神交它(开玩笑,精神文档/教程是相当确定)
上的严重帐户:这是更灵活
- 可扩展到解析其他结构元件,更复杂的
- 可以即时实现语义
- 将解析楠+/-无穷正确
- 等。
看到它Live on Coliru以及
当您需要重复某些操作的次数可变时,您通常需要做什么?你会用什么样的数据结构来存储可变数量的项目? – jamesdlin
@ÖöTiib:我不好,我会解决这个问题。 – Jessica
@ÖöTiib虽然OP没有说清楚,但通常情况下,输入以元素数量的非正值表示。所以,OP应该改变这个条件。 –