如何反转 C++ 向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8877448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I reverse a C++ vector?
提问by SirYakalot
Is there a built-in vector function in C++ to reverse a vector in place?
C++ 中是否有内置的向量函数来反转向量?
Or do you just have to do it manually?
或者你只需要手动完成?
回答by Ivaylo Strandjev
There's a function std::reverse
in the algorithm
header for this purpose.
为此std::reverse
,algorithm
标题中有一个函数。
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
回答by Xeo
All containers offer a reversed viewof their content with rbegin()
and rend()
. These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.
所有容器都使用和提供其内容的反向视图。这两个函数返回所谓的反向迭代器,它可以像普通的一样使用,但看起来容器实际上是反向的。rbegin()
rend()
#include <vector>
#include <iostream>
template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
--last;
for(; first != last; ++first){
std::cout << *first << delim;
}
std::cout << *first;
}
int main(){
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a+5);
print_range(v.begin(), v.end(), "->");
std::cout << "\n=============\n";
print_range(v.rbegin(), v.rend(), "<-");
}
Live example on Ideone. Output:
Ideone 上的现场示例。输出:
1->2->3->4->5
=============
5<-4<-3<-2<-1
回答by Chuck Norris
You can use std::reverse
like this
您可以使用std::reverse
这样的
std::reverse(str.begin(), str.end());
回答by Hello W
You can also use std::list
instead of std::vector
. list
has a built-in function list::reversefor reversing elements.
您也可以使用std::list
代替std::vector
。list
有一个内置函数list::reverse用于反转元素。
回答by gaurav raj
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector <int> v ;
vector <int> :: iterator it;
// Inserting elements in vector
for (int i = 0; i < 8; i++)
v.push_back(i+10);
cout<<"\nBefore Reversing: "<<endl;
for (it = v.begin(); it != v.end(); it++)
cout << (*it) << " ";
// Reversing elements
reverse(v.begin(), v.end());
cout << "\nAfter Reversing : \n";
for (it = v.begin(); it != v.end(); it++)
cout << (*it) << " ";
return 0; `enter code here`
}