[英]C++ appending to vector of strings efficiently (and idiomatically)
如果我想用 C++ 中的文件中的行填充字符串向量,将push_back
与std::move
一起使用是个好主意吗?
{
std::ifstream file("E:\\Temp\\test.txt");
std::vector<std::string> strings;
// read
while (!file.eof())
{
std::string s;
std::getline(file, s);
strings.push_back(std::move(s));
}
// dump to cout
for (const auto &s : strings)
std::cout << s << std::endl;
}
或者是否有其他一些变体,我只需 append 一个新的字符串实例到向量并获取它的引用?
例如我可以
std::vector<std::string> strings;
strings.push_back("");
string &s = strings.back();
但我觉得必须有更好的方法,例如
// this doesn't exist
std::vector<std::string> strings;
string & s = strings.create_and_push_back();
// s is now a reference to the last item in the vector,
// no copying needed
除了eof
误用之外,这几乎是惯用的做法。 下面是正确的代码:
std::string s;
while(std::getline(file, s))
{
strings.push_back(std::move(s));
s.clear();
}
请注意显式s.clear()
调用:对于从 object std::string
移出的唯一保证是您可以在没有先决条件的情况下调用成员函数,因此清除字符串应将其重置为“新” state,因为不能保证此举会对 object 做任何事情,而且你不能指望getline
不做任何奇怪的事情。
还有其他一些方法可以说明这一点(您可能可以使用istream_iterator
和适当的空白设置来实现类似的效果),但我认为这是最清楚的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.