C++ vector sort
To sort a vector in C++, you can use the sort()
function from the <algorithm>
library. Here are the steps involved in sorting a vector using the sort()
function:
Include the necessary headers:
cpp #include <vector> #include <algorithm>
This allows you to use the vector and algorithm functions.Create a vector:
cpp std::vector<int> numbers = {5, 2, 8, 3, 1};
This creates a vector callednumbers
and initializes it with some values.Sort the vector:
cpp std::sort(numbers.begin(), numbers.end());
This line of code sorts the elements in thenumbers
vector in ascending order. Thebegin()
andend()
functions are used to specify the range of elements to be sorted.Print the sorted vector:
cpp for (int num : numbers) { std::cout << num << " "; }
This loop iterates over each element in thenumbers
vector and prints it. After sorting, the output will be in ascending order:1 2 3 5 8
.
That's it! Following these steps will allow you to sort a vector in C++ using the sort()
function.