【发布时间】:2016-01-02 21:28:08
【问题描述】:
我正在尝试找到一种更有效的方法将整个文件读入行向量,定义为std::vector<std::string>。
目前,我写的很幼稚:
std::ifstream file{filepath};
std::vector<std::string> lines;
std::string line;
while(std::getline(file, line)) lines.push_back(line);
但感觉push_back 中的额外副本和每行的向量重新分配对效率极为不利,我正在寻找更现代的 c++ 类型的方法,such as using stream buffer iterators when copying bytes:
std::ifstream file{filepath};
auto filesize = /* get file size */;
std::vector<char> bytes;
bytes.reserve(filesize);
bytes.assign(std::istreambuf_iterator{file}, istreambuf_iterator{});
有没有这样的方法可以将文本文件逐行读取到向量中?
【问题讨论】:
-
如果您使用
std::move(line),push_back将不会复制。 -
@JonathanPotter 在
move之后再次使用对象?不喜欢那样。不过,我会使用emplace_back。 -
流迭代器方法在我的测试中非常慢。为了获得最大速度,我会尝试将整个文件读入一个预先分配的向量中,然后从那里将其拆分为单独的字符串。
-
@CoffeeandCode
move保证将移出的对象保持在一致的状态,所以我没有看到问题。 -
@Galik:要么重新分配旧字符串,要么在向量中分配新字符串,对此您无能为力。至少你没有复制实际的字符。