vendredi 28 septembre 2018

Is there a better way to print vector elements using iterator and reverse_iterator

I have a program that creates a 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 dthis: :-

    #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;
    }

Aucun commentaire:

Enregistrer un commentaire