避免原始循环并改用 std::algorithm

Han*_*lil 3 c++ stl-algorithm c++11

我正在尝试遵循此处给出的建议,以避免原始循环并std::algorithm改为使用。因此,如果您能在以下情况下帮助我做到这一点,我将不胜感激:

std::stringstream ss;
std::vector<Object> v;
for (const auto& curr : v) { ss << curr.ToString() << '\n'}
return ss.str()
Run Code Online (Sandbox Code Playgroud)

lcs*_*lcs 6

当然,你可以运行:

std::for_each(v.begin(), v.end(), [&](const Object& o) { ss << o.ToString() << '\n'; });
Run Code Online (Sandbox Code Playgroud)

这相当于

for(const auto&& curr : v)
{
  ss << curr.ToString() << '\n';
}
Run Code Online (Sandbox Code Playgroud)

这似乎是循环正常的情况。事实上,如果你看std::for_each代码,它只是在内部运行一个循环,所以它可能有点矫枉过正。


Sme*_*eey 5

这是非常简洁的:

std::copy(v.begin(), v.end(), std::ostream_iterator<Object>(std::cout, "\n"));
Run Code Online (Sandbox Code Playgroud)

例如,它只有在operator<<适当定义的情况下才有效

std::ostream& operator<<(std::ostream& ostr, const Object& obj)
{
    return ostr << obj.ToString();
}
Run Code Online (Sandbox Code Playgroud)