以下是一个使用C++98标准的例子,对map中的value进行升序排序,并输出key的一个向量:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

int main() {
    std::map<std::string, int> myMap;
    myMap["apple"] = 5;
    myMap["banana"] = 2;
    myMap["orange"] = 3;
    myMap["kiwi"] = 1;

    // 定义一个vector来存储key
    std::vector<std::string> keyVector;

    // 遍历map,并将key存入vector
    for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
        keyVector.push_back(it->first);
    }

    // 对vector进行排序
    std::sort(keyVector.begin(), keyVector.end());

    // 输出排序后的key
    for (std::vector<std::string>::iterator it = keyVector.begin(); it != keyVector.end(); ++it) {
        std::cout << *it << std::endl;
    }

    return 0;
}

输出结果为:

apple
banana
kiwi
orange

在上面的例子中,首先创建了一个std::map<std::string, int>类型的对象myMap,然后向其中插入了一些键值对。接着,使用一个std::vector<std::string>类型的对象keyVector来存储map中的key。通过遍历map,将key依次插入vector中。最后,使用std::sort对vector进行排序,并逐个输出排序后的key。

linux cc++ mapstring int c++使用c++98标准 value 进行排序升序输出key的一个向量给出使用例子

原文地址: https://www.cveoy.top/t/topic/i4KX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录