数据结构中的hash应用——平衡树模板实现的HASH模板map
c++map的底层实现原理
C++ STL中的map是一种关联容器,它存储的是键值对(key-value pairs),其中每个键key都是唯一的,通过键可以快速访问到相关联的值value。
map的底层实现一般使用平衡查找树,如红黑树(Red-Black Tree),这确保了在最坏的情况下,搜索、插入和删除操作都具有对数平均时间复杂度。
在C++中,map的底层实现可能会随着不同的STL实现而变化,但大多数现代C++编译器中使用的是基于红黑树的实现。
Map的遍历样例
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> exampleMap;
// 插入元素
exampleMap[1] = "one";
exampleMap[2] = "two";
exampleMap[3] = "three";
// 访问元素
cout << "Key 2 corresponds to value: " << exampleMap[2] << endl;
// 遍历元素
for (const auto &pair : exampleMap) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
return 0;
}
map的使用样例:统计字符串出现次数
Let the balloon rise
#include <iostream>
#include <map>
using namespace std;
map<string,int> mp;
int main(int argc, char** argv) {
int a;
string c,d;
while(cin>>a){
mp.clear();
if(a==0)
break;
int b=0;
for(int i=0;i<a;i++){
cin>>c;
mp[c]++;
if(b<mp[c]){
b=mp[c];
d=c;
}
}
cout<<d;
}
return 0;
}
使用遍历方式:
#include <iostream>
#include <map>
using namespace std;
map<string, int> mp;
int main()
{
int n, i;
int T;
string s;
string ms;
int duo;
while (cin >> n)
{
if (0 == n) break;
mp.clear();
for (i = 1; i <= n; i++){
cin >> s; mp[s]++;
}
duo = 0; ms = "";
for (const auto &pair: mp)
{
if (pair.second > duo)
{
duo = pair.second; ms = pair.first;
}
}
cout << ms << endl;
}
return 0;
}
对应练习:
Luogu p1184
HDU 1075
Luogu P2580
Luogu P1571
Luogu P1201
Luogu P3879
Luogu B3927