linux cc++ mapstring int c++使用c++98标准 使用value 进行排序升序输出key的一个向量给出使用例子
使用C++98标准对map<string, int>按照值进行升序排序,并输出键的向量的例子如下:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
// 自定义比较函数,用于按照值进行升序排序
struct CompareByValue {
bool operator()(const std::pair<std::string, int>& lhs, const std::pair<std::string, int>& rhs) const {
return lhs.second < rhs.second;
}
};
int main() {
std::map<std::string, int> myMap;
myMap["apple"] = 3;
myMap["banana"] = 2;
myMap["orange"] = 5;
myMap["grape"] = 4;
myMap["pineapple"] = 1;
// 将map中的键值对存入向量pairs
std::vector<std::pair<std::string, int> > pairs(myMap.begin(), myMap.end());
// 使用自定义的比较函数对向量进行排序
std::sort(pairs.begin(), pairs.end(), CompareByValue());
// 输出排序后的键的向量
std::cout << "Sorted keys in ascending order of values:" << std::endl;
for (std::vector<std::pair<std::string, int> >::iterator it = pairs.begin(); it != pairs.end(); ++it) {
std::cout << it->first << std::endl;
}
return 0;
}
输出结果:
Sorted keys in ascending order of values:
pineapple
banana
apple
grape
orange
在这个例子中,我们首先创建了一个map<string, int>,并向其中插入了一些键值对。然后,我们将map中的键值对存入了一个向量pairs,并使用自定义的比较函数CompareByValue对向量进行排序。最后,我们遍历排序后的向量,输出了键的向量,即按照值进行升序排序后的键的顺序。
原文地址: https://www.cveoy.top/t/topic/i4Lg 著作权归作者所有。请勿转载和采集!