在 C++ 中按值对 map 进行排序
本文将演示有关如何使用 C++ 中的值对 map
进行排序的多种方法。
使用 std::vector
和 std::sort
算法在 C++ 中按值对 map 元素进行排序
std::map
是一个关联容器,可以存储具有唯一键的键值对,后者用于自动对对象中的元素进行排序。在这种情况下,我们声明了一个示例 std::map
对象,其中整数字符串作为键,常规字符串作为值。问题是按字符串的值对这些元素进行排序。
我们不能在 std::map
结构上直接使用 std::sort
算法,因此我们必须初始化另一个可以排序的对象。因此,std::vector
的声明包含相同类型的对。我们使用 for
循环和 emplace_back
方法构造 vector
元素。一旦执行了循环,就可以将 vector
传递给 std::sort
算法了。请注意,我们指定了 lambda 表达式来定义元素比较功能,并且它仅比较第二个成员。最后,我们可以将 std::vector
元素输出为已排序的 map 表示形式。
#include <iostream>#include <map>#include <vector>using std::cout; using std::cin;
using std::endl; using std::map;
using std::string; using std::vector;
int main(){
map<string, string> veggy_map = {{"1", "Yam",},
{"2", "Pumpkin",},
{"3", "Ginger",},
{"4", "Melon",},
{"5", "Beetroot",},
{"6", "Spinach",}};
cout << "Unsorted - " << endl;
for (const auto & [key, value] : veggy_map) {
cout << key << " : " << value << endl;
}
vector<std::pair<string, string> > arr;
for (const auto &item : veggy_map) {
arr.emplace_back(item);
}
std::sort(arr.begin(), arr.end(),
[] (const auto &x, const auto &y) {return x.second < y.second;});
cout << "Sorted - " << endl;
for (const auto & [key, value] : arr) {
cout << key << " : " << value << endl;
}
return EXIT_SUCCESS;
}
输出:
Sorted -
5 : Beetroot
3 : Ginger
4 : Melon
2 : Pumpkin
6 : Spinach
1 : Yam
在 C++ 中使用 std::map
和 std::map::emplace
按值对 map 元素进行排序
先前的解决方案未处理 std::map
对象本身,而是使用外部结构进行排序。在这种情况下,我们实现了一种解决方案,将按值排序的元素存储在另一个 std::map
对象中。这可以通过 map 内置的 emplace
函数来实现。即,我们声明另一个 map
对象,并使用 emplace
方法构造其元素,但是我们还传递了反向键-值对。结果,map
容器通过键自动对元素进行排序:上一个 map
对象中的值。接下来,我们可以将排序后的 map
对象用于以下代码块中可能需要的其他操作,而不必担心它存储在其他对象中。
#include <iostream>#include <map>#include <vector>using std::cout; using std::cin;
using std::endl; using std::map;
using std::string; using std::vector;
int main(){
map<string, string> veggy_map = {{"1", "Yam",},
{"2", "Pumpkin",},
{"3", "Ginger",},
{"4", "Melon",},
{"5", "Beetroot",},
{"6", "Spinach",}};
cout << "Unsorted - " << endl;
for (const auto & [key, value] : veggy_map) {
cout << key << " : " << value << endl;
}
cout << "Sorted - " << endl;
map<string, string> veggy_map2;
for (const auto & [key, value] : veggy_map) {
veggy_map2.emplace(value, key);
}
for (const auto & [key, value] : veggy_map2) {
cout << value << " : " << key << endl;
}
return EXIT_SUCCESS;
}
输出:
Sorted -
5 : Beetroot
3 : Ginger
4 : Melon
2 : Pumpkin
6 : Spinach
1 : Yam
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。