C++中,哈希表的思想由STL中的unordered_map和unordered_set封装好。
下面依次介绍这俩的用法。
1. unordered_set
作为C++ STL中的哈希集合容器,用于存储不重复元素的集合。它提供了快速的查找、插入和删除操作,平均时间复杂度为常数。
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> mySet;
// 插入元素
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// 查找元素
if (mySet.find(20) != mySet.end()) {
std::cout << "Element 20 found in set." << std::endl;
} else {
std::cout << "Element 20 not found in set." << std::endl;
}
// 删除元素
mySet.erase(20);
// 遍历集合
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
// 统计元素个数
std::cout << "Size of set: " << mySet.size() << std::endl;
// 检查集合是否为空
if (mySet.empty()) {
std::cout << "Set is empty." << std::endl;
} else {
std::cout << "Set is not empty." << std::endl;
}
return 0;
}
2. unordered_map
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<int, std::string> myMap;
// 插入键值对
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 查找元素
if (myMap.find(2) != myMap.end()) {
std::cout << "Key 2 found in map. Value is: " << myMap[2] << std::endl;
} else {
std::cout << "Key 2 not found in map." << std::endl;
}
// 删除键值对
myMap.erase(2);
// 遍历map
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 统计元素个数
std::cout << "Size of map: " << myMap.size() << std::endl;
// 检查map是否为空
if (myMap.empty()) {
std::cout << "Map is empty." << std::endl;
} else {
std::cout << "Map is not empty." << std::endl;
}
return 0;
}
关于find函数,std::unordered_map
的find
函数用于查找特定的键是否存在于unordered_map
中。这个函数返回一个迭代器,指向包含指定键的元素,一般当判断用,不直接用返回值,如果键不存在,则返回指向unordered_map
末尾的迭代器(即end()
)。
在这种情况下,myMap.find(2)
尝试在myMap
中查找键为2的元素。如果找到了键为2的元素,则find
函数返回指向该元素的迭代器;如果没有找到,则返回myMap.end()
,表示未找到该元素。
P1. 洛谷p3405省市
#include<iostream>
#include<unordered_map>
#include<cstring>
using namespace std;
int nums=0;
string firsttwo(string s)
{
string f="";
f+=s[0];
f+=s[1];
return f;//注意写法
}
/*在C++的std::unordered_map中,通过mymap[key]访问元素时,key是用来检索值的,而不是键。如果键值对是"a"对应于"b",那么mymap["a"]将返回"b"。
如果你尝试使用mymap["b"]来获取键,则会根据"b"这个键检索对应的值。如果"b"不是std::unordered_map中的一个键,这将导致它被插入到std::unordered_map中,
并且对应的值将是std::string的默认值,即空字符串。*/
int main()
{
int n;cin>>n;
unordered_map<string,string> mymap;//键值混搭
for(int i=1;i<=n;i++)
{
string a,b;
cin>>a>>b;
mymap[a]=b;
mymap[b]=a;
}
for(const auto& pair:mymap)
{
string curcity=pair.first;
string curpro=pair.second;
string curfirst=firsttwo(curcity);
if(firsttwo(mymap[curfirst])==curpro) nums++;
}
cout<<nums/2;
return 0;
}
//可以用map数组,map[a]对应一堆map,其中b作索引,c作值.