题解:哈希表的插入更新,查询,删除,统计总数 (外加遍历)

unordered_map<string,int> haxi;

插入:haxi.insert({”wangwu“,10});

可插入可覆盖:haxi[wangwu]=20;

查询:haxi.count(wangwu)返回值为1,则存在;返回值为0,则不存在;

查询: auto it = hashTable.find(targetKey);

if (it != hashTable.end()) {

cout << "找到键 " << targetKey << ",值为:" << it->second << endl;}

else {

cout << "未找到键 " << targetKey << endl;

}

删除;haxi.earse(wangwu)返回1,删除成功;返回0,不存在;

统计总数:haxi.size()返回键值对;

遍历:

// 方式1:范围 for 循环(C++11 及以上,最简洁)

for (auto& pair : haxi) {

cout << "键:" << pair.first << ",值:" << pair.second << endl;

}

// 方式2:迭代器遍历(兼容低版本 C++)

// for (auto it = haxi.begin(); it != haxi.end(); ++it) {

// cout << "键:" << it->first << ",值:" << it->second << endl;

// }