sort a vector c++

To sort a vector in C++, you can use the sort function from the <algorithm> library. Here are the steps to do so:

  1. Include the necessary header files: cpp #include <vector> #include <algorithm>

  2. Declare and initialize a vector: cpp std::vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5};

  3. Sort the vector using the sort function: cpp std::sort(myVector.begin(), myVector.end());

This function takes two arguments: the beginning and end iterators of the range to be sorted.

  1. Print the sorted vector: cpp for (const auto& element : myVector) { std::cout << element << " "; }

This loop iterates over each element in the vector and prints it.

The output of the above code will be the sorted vector: 1 1 2 3 4 5 5 6 9.

That's it! The vector is now sorted in ascending order using the sort function.