To sort an array in C++, you can use the std::sort() function from the algorithm library.
In this example,
numbers
with values 5, 2, 8, 1, 6.std::sort()
function from the algorithm library to sort the vector in ascending order.numbers
to the console.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 6};
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted array in ascending order: ";
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Sorted array in ascending order: 1 2 5 6 8
In this example,
numbers
with values 5, 2, 8, 1, 6.compare
that sorts in descending order.std::sort()
function with our custom comparator to sort the vector in descending order.numbers
to the console.#include <iostream>
#include <vector>
#include <algorithm>
bool compare(int a, int b) {
return a > b;
}
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 6};
std::sort(numbers.begin(), numbers.end(), compare);
std::cout << "Sorted array in descending order: ";
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Sorted array in descending order: 8 6 5 2 1
In this tutorial, we learned How to Sort an Array in C++ language with well detailed examples.