Sorting a vector in C++ is a common operation that can be easily accomplished using the std::sort function from the <algorithm> library. The std::sort function is powerful and flexible, allowing you to sort vectors in ascending, descending, or custom order with ease.
std::sort for Ascending Order
The simplest way to sort a vector in ascending order is to use the std::sort function, which sorts the elements between two iterators, typically begin() and end().
Example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {4, 2, 7, 1, 9};
std::sort(numbers.begin(), numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Output:
1 2 4 7 9
To sort a vector in descending order, you can pass the std::greater<int>() comparator to the std::sort function.
Example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {4, 2, 7, 1, 9};
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Output:
9 7 4 2 1
If you need a custom sort order, you can provide a custom comparator function or lambda expression. The comparator should return true if the first element should appear before the second.
Example:
#include <algorithm>
#include <iostream>
#include <vector>
bool customSort(int a, int b) {
// Sort based on even numbers first, then by ascending order
if ((a % 2 == 0) && (b % 2 != 0)) return true;
if ((a % 2 != 0) && (b % 2 == 0)) return false;
return a < b;
}
int main() {
std::vector<int> numbers = {4, 2, 7, 1, 9};
std::sort(numbers.begin(), numbers.end(), customSort);
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Output:
2 4 1 7 9
1. Sorting a vector of strings in alphabetical order:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words = {"apple", "orange", "banana", "grape"};
std::sort(words.begin(), words.end());
for (const auto& word : words) {
std::cout << word << " ";
}
return 0;
}
Output:
apple banana grape orange
2. Sorting a vector of pairs by the second element:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::pair<int, int>> pairs = {{1, 5}, {2, 3}, {4, 2}};
std::sort(pairs.begin(), pairs.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
for (const auto& p : pairs) {
std::cout << "{" << p.first << ", " << p.second << "} ";
}
return 0;
}
Output:
{4, 2} {2, 3} {1, 5}
For more information, check out the official C++ documentation:
Jorge García
Fullstack developer