替换' for循环'使用std :: for_each

时间:2016-02-08 16:56:08

标签: c++ std

我在下面的代码中有一个for循环,我想用std :: for_each实现它。我已经实现了它。有人可以告诉我,如果这是使用std :: for_each做到这一点的最好方法吗?如果没有,你能建议合适吗?

#include <vector>
#include <cstdint>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>

int main()
{
    std::vector<std::uint32_t> nums{3, 4, 2, 8, 15};
    std::stringstream list1;


    for (auto n : nums)
    {
        list1 << n<<",";
    }

    //Is this the right way to do using std::for_each so that above for loop can be done in 1 line??
    std::for_each(nums.begin(),nums.end(),[&list1](std::uint32_t n){ list1 << n << ","; });

}

4 个答案:

答案 0 :(得分:3)

是的,您使用for_each是前一循环的合理模拟。

然而,我不得不指出,我发现for_each可能是库中最少的有用算法。从我所看到的,使用它通常表明你仍然基本上思考的循环,只是改变你用于这些循环的语法。我还认为基于范围的for循环可能已经消除了for_each过去至少90%(已经很少)的合法用途。

在这种情况下,您的代码实际上是在模仿std::copy使用std::ostream_iterator

std::copy(nums.begin(), nums.end(), 
          std::ostream_iterator<std::uint32_t>(std::cout, ","));

然而,即使这样也很笨拙,我认为它是否真的比基于范围的for循环真的有所改进。

答案 1 :(得分:1)

你为什么不试试呢?

auto vs std::for_each

如您所见,两者的装配输出相同。它对你的例子没有任何影响。

答案 2 :(得分:0)

如果您想将数据从一件事复制到另一件事,您可以使用std::copy

int main()
{
    std::vector<std::uint32_t> nums{3, 4, 2, 8, 15};
    std::stringstream list1;

    std::copy(nums.begin(), nums.end(),std::ostream_iterator<std::uint32_t>(list1,","));
    std::cout << list1.str();
}

Live Example

这将使用,结束流,但这与您在代码中获得的内容相同。

如果您不想这样,那么您应该查看Pretty-print C++ STL containers

答案 3 :(得分:-4)

是的,这是对的。如果您将表现作为动机,则(std::uint32_t &n)中无需参考。

相关问题