输出一个数字数组,而不必单独输出其中的每个值

Output an array of numbers without having to output each value in it separately?

本文关键字:输出 单独 不必 一个 数组 数字      更新时间:2023-10-16

我已经通过"cout"数字[1]、数字[2]等输出了数组中的每个值。我想知道是否有可能一次"计数"一个值代表数组中的所有数字。

int numbers [ ] = { 40, 20, 50, 60, 10, 15 } ;

你可以使用循环,例如

for( int const x : numbers )
{
    cout << x << endl;
}

您可以使用std::copy()std::begin()std::end()辅助函数来为您的数组创建范围。然后使用std::ostream_iterator<int>放置输出:

#include <algorithm>
#include <iterator>
std::copy(std::begin(numbers),
          std::end(numbers), std::ostream_iterator<int>(std::cout));