I have a program that creates a std::vector
and adds the given values to it using push_back()
. The expected output is to print the vector values in default order and reverse order using an iterator and reverse iterator. The output is absolutely correct but I was just wondering if there's a better way to do this: :-
#include <iostream>
#include <vector>
using namespace std;
vector<int> myvector;
int i;
int main()
{
int n;
cin>>n;
int input;
for (i = 0; i < n; i++)
{
cin >> input;
myvector.push_back(input);
}
for (int i = 0; i < n; i++)
{
cout<<" "<<myvector[i]; //prints user vector input
}
cout<<endl;
typedef vector<int>::iterator iter_type;
iter_type from (myvector.begin());
iter_type until (myvector.end());
reverse_iterator<iter_type> rev_until (from);
reverse_iterator<iter_type> rev_from (until);
while (rev_from != rev_until)
cout << ' ' << *rev_from++; //prints reversed vector
return 0;
}
Figured out an alternate method
#include <vector>
#include <iostream>
int main()
{
int n;
std::cin>>n;
std::vector<int> g1;
int a[40];
std::vector<int>::iterator i;
std::vector<int>::reverse_iterator it;
for(int i=0;i<n;i++)
{
std::cin>>a[i];
g1.push_back(a[i]);
}
for (auto i = g1.begin(); i != g1.end(); ++i)
std::cout << *i << " ";
std::cout<<"\n";
for (auto it = g1.rbegin(); it != g1.rend(); ++it)
std::cout << *it << " ";
return 0;
}