STL中vector容器实现反转(reverse)
vector容器中实现可以通过以下两种方式实现:
#include "stdafx.h" #include <vector> #include <iostream> //#include <math.h> #include <algorithm> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<int> arrayInt; arrayInt.resize(10); for (int i=0;i<10;i++) { arrayInt[i]=i; } vector<int> arrayRever; arrayRever.reserve(arrayInt.size()); //vector反转 //------------------------------------------------------------------------------ //>>> //方法一:使用vector自带的反转迭代器reverse_iterator,rbegin(),rend() vector<int>::reverse_iterator riter; for (riter=arrayInt.rbegin();riter!=arrayInt.rend();riter++) { arrayRever.push_back(*riter); } //<<< //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //>>> //方法二:使用<algorthm>中的reverse() //arrayRever=arrayInt; //reverse(arrayRever.begin(),arrayRever.end()); //<<< //------------------------------------------------------------------------------ // for (int i=0;i<arrayRever.size();i++) { cout<<"arrayRever["<<i<<"]"<<" "<<arrayRever[i]<<endl; } return 0; }
知识就是力量!