有几种方法可以完成您正在寻找的东西,在这篇文章中,我将描述三种不同的方法。他们三个都假设您使用std::ifstream ifs ("filename.txt") 打开文件,并且您的“array”实际上是一个声明为std::vector<int> v 的向量。
在这篇文章的最后,还有一些关于如何加快插入向量的建议。
我想保持简单..
最简单的方法是使用operator>> 一次读取一个char,然后从返回的值中减去'0'。
'0' 到 '9' 的标准保证是连续的,并且由于 char 只是以不同方式打印的数值,因此可以隐式转换为 int。
char c;
while (ifs >> c)
v.push_back (c - '0');
我喜欢 STL,讨厌写循环......
这将被许多人视为“c++ 实现方式”,尤其是如果您正在与 STL-fanboys 交谈,尽管它需要编写更多代码..
#include <algorithm>
#include <functional>
#include <iterator>
...
std::transform (
std::istream_iterator<char> (ifs),
std::istream_iterator<char> (),
std::back_inserter (v),
std::bind2nd (std::minus<int> (), '0')
);
我不想写循环,但为什么不使用 lambda? c++11
#include <algorithm>
#include <functional>
#include <iterator>
...
std::transform (
std::istream_iterator<char> (iss),
std::istream_iterator<char> (),
std::back_inserter (v),
[](char c){return c - '0';}
);
我的std::vector 会在每次插入时重新分配存储空间吗?
是的,可能。为了加快速度,您可以在开始执行任何插入之前在向量中保留存储空间,如下所示。
ifs.seekg (0, std::ios::end); // seek to the end of your file
v.reserve (ifs.tellg () ); // ifs.tellg () -> number of bytes in it
ifs.seekg (0, std::ios::beg); // seek back to the beginning