C++ 有效地(并且惯用地)附加到字符串向量

C++ appending to vector of strings efficiently (and idiomatically)

如果我想用 C++ 中文件中的行填充字符串向量,使用 push_backstd::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;
}

或者是否有一些其他变体,我可以简单地将一个新的字符串实例附加到向量并获取它的引用?

例如我可以

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() 调用:对移出对象 std::string 的唯一保证是您可以在没有先决条件的情况下调用成员函数,因此清除字符串应将其重置为一个“新鲜”状态,因为移动不能保证对对象做任何事情,你不能依赖 getline 不做任何奇怪的事情。

还有其他一些方法可以说明这一点(您可能可以通过 istream_iterator 和适当的空白设置实现类似的效果),但我认为这是最清楚的。