如果我创建了一个矢量:
vector<int> numbers;
并推送一些值:
for (int i=1; i<=39; ++i) numbers.push_back(i);
我怎样才打印出例如1到10的数字?
此后,打印15-30,因此numbers.begin()
可能不适用于那里。
答案 0 :(得分:3)
我怎样才打印出例如1到10的数字?
std::copy(numbers.begin(), numbers.begin() + 10, std::ostream_iterator(std::cout, " ");
此后,打印15-30
std::copy(numbers.begin() + 15, numbers.begin() + 30, std::ostream_iterator(std::cout, " ");
如果您有权访问Range-V3 library ...您还可以:
for(auto x : numbers | ranges::view::slice(0, 10))
std::cout << x << " ";
...今天,您可以将整个代码缩小到:
#include <iostream>
#include <range/v3/all.hpp>
int main () {
std::vector<int> numbers = ranges::view::closed_iota(1, 40);
ranges::copy(numbers | ranges::view::slice(0, 10), ranges::ostream_iterator<int>(std::cout, " "));
std::endl(std::cout);
ranges::copy(numbers | ranges::view::slice(15, 30), ranges::ostream_iterator<int>(std::cout, " "));
}
输出:
1 2 3 4 5 6 7 8 9 10
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
请注意, Ranges-TS 正在管道中,以包含在下一个C ++标准中。也许C ++ 20?
完整示例使用Range-V3 Live On Coliru