一段代码:std::unordered_map,->、.

108 阅读1分钟
#include <unordered_map>
#include <iostream>

int main() {
    std::unordered_map<int, std::string> m_pluginRenderMap;
    std::unordered_map<int, std::string> umap = {{1, "one"}, {2, "two"}, {3, "three"}};
    m_pluginRenderMap.insert({1, "one"});  // 使用 insert() 插入键值对
    m_pluginRenderMap.emplace(2, "two");   // 使用 emplace() 原地构造键值对
    
    for (auto it = umap.begin(); it != umap.end(); ++it) 
    {
         std::cout << it->first << ": " <<    it->second << std::endl; 
    }
    
    umap.erase(2); // 删除键为 2 的元素 
    for (const auto& pair : umap) { 
         std::cout << pair.first << ": " << pair.second << std::endl; 
    }
    
     auto it = umap.find(2);  // 查找键为 2 的元素
    if (it != umap.end()) {
        std::cout << "Found: " << it->first << ": " << it->second << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    // 若键不存在,operator[] 会插入一个新的元素,at() 则会抛出异常
    std::cout << umap[3] << std::endl;      // 输出空字符串,并插入 {3, ""}
    try {
        std::cout << umap.at(4) << std::endl;  // 抛出异常
    } catch (const std::out_of_range& e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}