C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ map对比

C++ 各种map特点对比分析

作者:越甲八千

文章比较了C++中不同类型的map(如std::map, std::unordered_map, std::multimap, std::unordered_multimap, hash_map)的底层实现、元素顺序、键的唯一性以及查找和插入删除操作的效率,感兴趣的朋友一起看看吧

特点比较

1. std::map

2. std::unordered_map

3. std::multimap

4. std::unordered_multimap

5. hash_map(SGI STL 扩展)

C++ 示例代码

#include <iostream>
#include <map>
#include <unordered_map>
#include <ext/hash_map>  // 对于支持 hash_map 的编译器
// 演示 std::map 的使用
void testStdMap() {
    std::map<int, std::string> myMap;
    myMap[1] = "apple";
    myMap[2] = "banana";
    myMap[1] = "cherry";  // 键 1 重复,会覆盖原有的值
    std::cout << "std::map:" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}
// 演示 std::unordered_map 的使用
void testUnorderedMap() {
    std::unordered_map<int, std::string> myUnorderedMap;
    myUnorderedMap[1] = "apple";
    myUnorderedMap[2] = "banana";
    myUnorderedMap[1] = "cherry";  // 键 1 重复,会覆盖原有的值
    std::cout << "\nstd::unordered_map:" << std::endl;
    for (const auto& pair : myUnorderedMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}
// 演示 std::multimap 的使用
void testMultiMap() {
    std::multimap<int, std::string> myMultiMap;
    myMultiMap.insert({1, "apple"});
    myMultiMap.insert({2, "banana"});
    myMultiMap.insert({1, "cherry"});  // 键 1 重复,允许插入
    std::cout << "\nstd::multimap:" << std::endl;
    for (const auto& pair : myMultiMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}
// 演示 std::unordered_multimap 的使用
void testUnorderedMultiMap() {
    std::unordered_multimap<int, std::string> myUnorderedMultiMap;
    myUnorderedMultiMap.insert({1, "apple"});
    myUnorderedMultiMap.insert({2, "banana"});
    myUnorderedMultiMap.insert({1, "cherry"});  // 键 1 重复,允许插入
    std::cout << "\nstd::unordered_multimap:" << std::endl;
    for (const auto& pair : myUnorderedMultiMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}
// 演示 hash_map 的使用
void testHashMap() {
    __gnu_cxx::hash_map<int, std::string> myHashMap;
    myHashMap[1] = "apple";
    myHashMap[2] = "banana";
    myHashMap[1] = "cherry";  // 键 1 重复,会覆盖原有的值
    std::cout << "\nhash_map:" << std::endl;
    for (const auto& pair : myHashMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}
int main() {
    testStdMap();
    testUnorderedMap();
    testMultiMap();
    testUnorderedMultiMap();
    testHashMap();
    return 0;
}

代码解释

需要注意的是,hash_map 不是标准 C++ 的一部分,如果你使用的编译器不支持 ext/hash_map 头文件,代码可能无法编译。建议优先使用标准的 std::unordered_map

到此这篇关于C++ 各种map对比的文章就介绍到这了,更多相关C++ map对比内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文