Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Reverse in C++

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 514
    Comment on it

    If you want to reverse the order of elements in a given range, then you can use the reverse function defined in the STL algorithm.

    Template for reverse

    template <class BidirectionalIterator>
      void reverse (BidirectionalIterator first, BidirectionalIterator last);
    

    About parameters
    InputIterator first
    InputIterator first for the initial position of the range which is included in the range.
    InputIterator last
    InputIterator last for the final position which it not included in the range.

    A sample program using reverse

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
            vector <int> v;
            vector <int>:: iterator it;
    
            // Pushing 11 random elements inside the vector
            v.push_back(11);
            v.push_back(10);
            v.push_back(9);
            v.push_back(8);
            v.push_back(7);
            v.push_back(6);
            v.push_back(5);
            v.push_back(4);
            v.push_back(3);
            v.push_back(2);
            v.push_back(1);
    
            // printing the elemnets inside the raange
            cout <<"Elements inside the range. " << endl;
            for ( it = v.begin(); it != v.end(); it++)
                    cout << *it << " ";
            cout << endl;
    
            //applying reverse function on the range
            reverse(v.begin(),v.end());
    
            // printing the elemnets inside the range
            cout <<"Elements inside the range after reverse. " << endl;
            for ( it = v.begin(); it != v.end(); it++)
                    cout << *it << " ";
            cout << endl;
    
            return 0;
    }
    

    Output of the above program

    Elements inside the range. 
    11 10 9 8 7 6 5 4 3 2 1 
    Elements inside the range after reverse. 
    1 2 3 4 5 6 7 8 9 10 11
    

    Time complexity for reverse is linear in half the distance between the range.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: