How to sort STL containers in C++: Use the sort() function to sort containers in place, such as std::vector. With ordered containers std::set and std::map, elements are automatically sorted on insertion. For a custom sort order, you can use a custom comparator class, such as sorting a vector of strings alphabetically.
STL (Standard Template Library) provides a series of flexible and efficient general algorithms for various types of containers operations, including sorting. The following sections describe several common ways to sort STL containers in C++.
std::sort()
The function is the simplest function in C++ for container sorting. It accepts a reference or pointer to a container as input and sorts its elements in place. The following example demonstrates how to use the sort()
function to sort a std::vector
:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {3, 1, 4, 2, 5}; // 使用 sort() 函数对向量进行排序 std::sort(v.begin(), v.end()); // 打印排序后的向量 for (int num : v) { std::cout << num << " "; } return 0; }
Output:
1 2 3 4 5
std::set
and std::map
are ordered containers in C++ , they maintain their own collection of elements and automatically sort elements upon insertion. The following example shows how to use std::set
to create and sort a set of integers:
#include <iostream> #include <set> int main() { std::set<int> s = {3, 1, 4, 2, 5}; // 由于 std::set 是有序的,元素按升序存储 for (int num : s) { std::cout << num << " "; } return 0; }
Output:
1 2 3 4 5
If you need to customize the sorting order, you can implement it through a custom comparator class. The following example shows how to create a custom comparator that sorts a vector of strings alphabetically:
#include <iostream> #include <vector> #include <algorithm> class StringComparator { public: bool operator()(const std::string& a, const std::string& b) const { return a < b; } }; int main() { std::vector<std::string> v = {"apple", "banana", "cherry", "dog", "elephant"}; // 使用自定义比较器对向量进行排序 std::sort(v.begin(), v.end(), StringComparator()); // 打印排序后的向量 for (const std::string& s : v) { std::cout << s << " "; } return 0; }
Output:
apple banana cherry dog elephant
The above is the detailed content of How to sort C++ STL containers?. For more information, please follow other related articles on the PHP Chinese website!