简体   繁体   English

以相反的顺序打印矢量

[英]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使用reverse_iterator而不是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输出将是: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):使用常量反向迭代器(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!为了检查我们是否到达了起点,我们可以使用迭代器变量(在我的例子中为 x)与 crend(返回向量的起点)进行比较。记住这里的一切都是相反的!

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.在 C++20 中,您可以使用在range 库中找到并由 gcc 10支持views::reverse

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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