如何使用for_each的输出来清点? [英] How do I use for_each to output to cout?

查看:142
本文介绍了如何使用for_each的输出来清点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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个元素,看<一href="http://stackoverflow.com/questions/3829885/how-to-copy-a-certain-number-of-chars-from-a-file-to-a-vector-the-stl-way">this问题。

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

这篇关于如何使用for_each的输出来清点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆