简体   繁体   中英

Printing vector in reverse order

Is there a better way of printing a vector in reverse order then this:

#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;

void print_elem(int elem)
{
    cout << elem << endl;    
}

int main()
{
    int ia[4]={1,2,3,4};
    vector<int> vec(ia,ia+4);
    reverse(vec.begin(), vec.end());
    for_each(vec.begin(),vec.end(),print_elem);
    reverse(vec.begin(), vec.end());
}

您可以使用反向迭代器:

for_each(vec.rbegin(),vec.rend(),print_elem);

There are many ways to print a bidirectional sequence in reverse without reversing the elements, eg:

std::copy(vec.rbegin(), vec.rend(), std::ostream_iterator<int>(std::cout, "\n"));
std::reverse_copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));

Use reverse_iterator instead of iterator

int main()
{
    int ia[4]={1, 2, 3, 4};
    vector<int> vec(ia,ia+4);
    for(vector<int>::reverse_iterator it = vec.rbegin; it != vec.rend(); ++it)
    {
        std::cout << *it << std::endl;
    }
}

The output will be: 4, 3, 2, 1

There are many ways to do this.I will just explain one, more can be seen in this link.

Using constant reverse iterator(crbegin):

Reverse iterators iterate backward ie increasing them moves them towards the beginning of the container.

To check if we have reached beginning, we can use the iterator variable(x in my case) to compare with crend (returns the starting of the vector).Remember everything is reverse here!

following is a simple implementation:

for(auto x = vec.crbegin() ; x!=vec.crend() ; x++){
        cout<<*x<<" ";
}

In C++20 you can utilize views::reverse found in ranges library and supported by gcc 10.

#include <iostream>
#include <vector>
#include <ranges>

int main()
{

        std::vector V{0, 1, 2, 3, 4, 5, 6, 7};
        for (auto v : V | std::views::reverse)
        {
                std::cout << v << " ";
        }
        return 0;
}

And the output is:

7 6 5 4 3 2 1 0

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