Sorting C++ unordered_map: Simple Guide
In C++, hash tables are unordered data structures, so they cannot be sorted directly. If sorting elements within a hash table is necessary, you can copy the elements to a new container (such as a vector) and then sort that container.
Here is a sample code demonstrating how to copy elements from a hash map to a vector and sort them.
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
int main() {
std::unordered_map<int, std::string> hashTable = {
{1, "apple"},
{3, "banana"},
{2, "orange"}
};
std::vector<std::pair<int, std::string>> vec(hashTable.begin(), hashTable.end());
// 对vector中的元素进行排序
std::sort(vec.begin(), vec.end(), [](const std::pair<int, std::string>& a, const std::pair<int, std::string>& b) {
return a.first < b.first;
});
// 打印排序后的结果
for (const auto& pair : vec) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
In the example above, the elements in the hash table are first copied to a vector, then the elements in the vector are sorted using the std::sort function, and finally the sorted results are printed.