How to Reverse the Order of a Vector in C++

How to Reverse the Order of a Vector in C++ thumbnail
A vector is an object that has data and function components.

C++ is an object oriented programming language. In layman's terms, C++ focus is to create reusable and modular code. Objects are complex structures that have data components and functions to operate in the data, all contained under a single structure. Vector objects are very useful because they are widely applied as they are often used in math physics and help model other data structures. Reversing the elements of a vector helps you understand the vector objects better.

Instructions

    • 1

      Start your program by including the "algorithm" library. The algorithm library contains general algorithms to sort, rearrange and handle data in structures such as lists, vectors and many more. Include also the "vector" library to enable the use of vectors.

      This is the code:

      #include<algorithm>

      #include<vector>

      int main()

      {

    • 2

      Declare a vector and initialize it to any set of values. C++ allows the user to declare vectors by using the "vector" template class followed by the data type that the vector contains. The program uses an integer array of five numbers called "SomeNumbers" to provide values for the vector.

      int SomeNumbers[5] = { 0, 1, 2, 3, 4, };

      vector<int> MyFirstVector ( SomeNumbers, SomeNumbers + 5 );

    • 3

      Use the "reverse()" function to reverse the order of the elements in the vector. The reverse function is a general function provided by the "algorithm" library, that swaps the order of the elements on a structure. The reverse function uses a range as parameters for the swap, allowing the user to reverse the whole structure or just parts of it.

      To reverse the complete vector, use the code:

      reverse( MyFirstVector.begin(), MyFirstVector.end() );

      MyFirstVector.begin() is an iterator that points to the beginning of the vector, and MyFirstVector.end() points to one position past the end of the vector.

    • 4

      End the program by returning any value.

      return(0);

      }

Tips & Warnings

  • Read the specifications of the vector object and experiment changing the range for the reverse() function.

  • For additional examples and output see the Cplusplus website.

  • On Step 2 do not change the order in which SomeNumbers and MyFirstVector are declared.

Related Searches:

References

  • Photo Credit Stockbyte/Stockbyte/Getty Images

Comments

You May Also Like

  • How to Use Excel's CUBESETCOUNT Function

    Excel's CUBESETCOUNT function returns the number of members in a set. It typically uses a CUBESET function or reference to a CUBESET...

  • Vector Cross Product Rules

    The cross product of two vectors yields a third vector in three-dimensional space. The resulting vector is perpendicular to both the cross-multiplied...

Related Ads

Featured