简体   繁体   中英

how to print range of integer values from a vector

If i create a vector:

vector<int> numbers;

and push some values in:

for (int i=1; i<=39; ++i) numbers.push_back(i);

how can i print out only numbers 1 through 10 for example?

Also after that, print out 15-30, so numbers.begin() isn't probably applicable there.

how can i print out only numbers 1 through 10 for example?

std::copy(numbers.begin(), numbers.begin() + 10, std::ostream_iterator(std::cout, " ");

Also after that, print out 15-30

std::copy(numbers.begin() + 15, numbers.begin() + 30, std::ostream_iterator(std::cout, " ");

If you have access to the Range-V3 library ... You can also:

for(auto x : numbers | ranges::view::slice(0, 10))
    std::cout << x << " ";

... Today, you can have the whole code narrowed to:

#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, " "));
}

Outputs:

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 

Note that Ranges-TS is on the pipeline for inclusion into the next C++ standard. C++20 perhaps?

Full example Using Range-V3 Live On Coliru

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM