如何使用for_each的输出来清点?如何使用、for_each

2023-09-11 00:29:21 作者:伤若堆成海

有没有更直接的方式来做到这一点?

Is there a more straight-forward way to do this?

的for_each(v_Numbers.begin(),v_Numbers.end(),bind1st(运营商<<,COUT));

如果没有一个明确的循环,如果可能的话。

Without an explicit for loop, if possible.

编辑:

如何做到这一点的的std :: CIN 的std ::矢量如果可能的话? (如何阅读 N 元素只)?

How to do this for std::cin with a std::vector if possible? (How to read n elements only)?

推荐答案

同样的事情也将是这样的:

Something similar would be this:

std::vector<int> v_Numbers; // suppose this is the type
// put numbers in
std::copy(v_Numbers.begin(), v_Numbers.end(),
            std::ostream_iterator<int>(cout));

如果你添加一些后缀这会更好:

It would be even nicer if you add some suffix:

std::copy(v_Numbers.begin(), v_Numbers.end(),
            std::ostream_iterator<int>(cout, "\n"));

这假定你的容器是矢量&lt; INT&GT; ,所以你将不得不更换了部分使用合适的类型

This assumes that your container is a vector<int>, so you will have to replace that part with the appropriate type.

修改

std::vector<int> v_Numbers;
std::copy(std::istream_iterator<int>(cin), std::istream_iterator<int>(),
              std::back_inserter(v_Numbers));

如果你想只读n个元素,看this问题。

If you want to read n elements only, look at this question.