2024年10月04日
(2024-10-04 20:13:21)#include
#include
#include
// 创建一个
unordered_map
std::unordered_map
wordCount;
// 插入元素
wordCount["apple"] =
1;
wordCount["banana"] =
2;
// 使用 insert
方法插入键值对
wordCount.insert({
"orange", 3 });
// 访问元素
std::cout <<
"Count for 'apple': " << wordCount["apple"] <<
std::endl;
// 检查键是否存在
if
(wordCount.find("banana") != wordCount.end()) {
std::cout << "'banana' is in the map."
<< std::endl;
}
// 遍历
unordered_map
std::cout << "All
elements in unordered_map:" << std::endl;
for (const auto&
pair : wordCount) {
std::cout << pair.first << ": "
<< pair.second << std::endl;
}
// 修改元素
wordCount["apple"] =
5;
// 删除元素
wordCount.erase("orange");
return 0;

int main() {
}
————————————————————————
代码可以大聪明写,
解释和描述 自己敲一波:
1、auto 让编译器 自己对 pair进行类型推导,可以是int
、char等。避免复杂类型声明。
2、const 是修饰pair,以防遍历过程中 键、值 任何被修改。
3、&表示引用,pair去引用 容器中的元素,避免拷贝。const
&,引用形式访问,并且不被修改,速度快。


后一篇:2024年10月04日

加载中…