#include \n#include \n#include \n#include \n\nint main() {\n std::map<std::string, int> myMap; \n myMap["apple"] = 5; \n myMap["banana"] = 2; \n myMap["orange"] = 3; \n myMap["kiwi"] = 1; \n\n // 定义一个vector来存储key \n std::vectorstd::string keyVector; \n\n // 遍历map,并将key存入vector \n for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {\n keyVector.push_back(it->first); \n } \n\n // 对vector进行排序 \n std::sort(keyVector.begin(), keyVector.end()); \n\n // 输出排序后的key \n for (std::vectorstd::string::iterator it = keyVector.begin(); it != keyVector.end(); ++it) {\n std::cout << *it << std::endl; \n } \n\n return 0; \n} \n\n输出结果为:\n\n\n\napple\nbanana\nkiwi\norange\n\n\n在上面的例子中,首先创建了一个std::map<std::string, int>类型的对象myMap,然后向其中插入了一些键值对。接着,使用一个std::vector<std::string>类型的对象keyVector来存储map中的key。通过遍历map,将key依次插入vector中。最后,使用std::sort对vector进行排序,并逐个输出排序后的key。

C++98: 使用map进行排序并输出key向量 -  升序排序示例

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

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