How to print a vector in reverse order with C++

3 Answers

0 votes
#include <iostream>
#include <vector>
#include <iterator>
 
void print(std::vector<char> const &v) {
    std::copy(v.rbegin(),
            v.rend(),
            std::ostream_iterator<char>(std::cout, " "));
}
 
int main()
{
    std::vector<char> v = {'a', 'b', 'c', 'd'};

    print(v);
 
    return 0;
}




/*
run:

d c b a 

*/

 



answered Feb 19, 2021 by avibootz
0 votes
#include <iostream>
#include <vector>

void print(std::vector<char> const &v) {
    for (auto it = v.crbegin(); it != v.crend(); it++) {
        std::cout << *it << ' ';
    }
}
 
int main()
{
    std::vector<char> v = {'a', 'b', 'c', 'd'};

    print(v);
 
    return 0;
}




/*
run:

d c b a 

*/

 



answered Feb 19, 2021 by avibootz
0 votes
#include <iostream>
#include <vector>

void print(std::vector<char> const &v) {
    for (int i = v.size() - 1; i >= 0; i--) {
        std::cout << v.at(i) << " ";
    }
}
  
int main()
{
    std::vector<char> v = {'a', 'b', 'c', 'd'};
 
    print(v);
  
    return 0;
}
 
 
 
 
/*
run:
 
d c b a 
 
*/

 



answered Feb 19, 2021 by avibootz

Related questions

2 answers 268 views
1 answer 192 views
1 answer 114 views
1 answer 124 views
1 answer 200 views
200 views asked Jul 22, 2020 by avibootz
1 answer 183 views
...