返回
STL容器妙用:map容器带你轻松管理数据
后端
2023-10-13 06:44:21
STL map容器介绍
STL map容器是存储pair类型键值对(pair类模板创建的pair对象)的关联式容器。pair键值对(pair<const K, T>):键值对中第一个元素为key(键),第二个元素为value(值)。map容器以键作为元素的唯一标识,并按照键的升序排列元素。
map容器的键必须是唯一的,而值可以是重复的。map容器提供了快速查找和检索元素的功能,时间复杂度为O(log n),其中n是容器中的元素个数。
map容器的使用方法
1. 创建map容器
创建map容器有两种常用的方法:
// 方法一:使用默认构造函数创建map容器
map<int, string> myMap;
// 方法二:使用带有初始键值对的构造函数创建map容器
map<int, string> myMap = {
{1, "one"},
{2, "two"},
{3, "three"}
};
2. 向map容器中插入元素
可以使用以下方法向map容器中插入元素:
// 方法一:使用insert()方法插入元素
myMap.insert(pair<int, string>(4, "four"));
// 方法二:使用[]运算符插入元素
myMap[5] = "five";
3. 查找map容器中的元素
可以使用以下方法查找map容器中的元素:
// 方法一:使用find()方法查找元素
auto it = myMap.find(3);
if (it != myMap.end()) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
// 方法二:使用[]运算符查找元素
cout << "Value of key 5: " << myMap[5] << endl;
4. 删除map容器中的元素
可以使用以下方法删除map容器中的元素:
// 方法一:使用erase()方法删除元素
myMap.erase(3);
// 方法二:使用clear()方法删除所有元素
myMap.clear();
map容器的应用实例
1. 统计单词出现次数
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// 创建map容器存储单词及其出现次数
map<string, int> wordCount;
// 读取输入的字符串
string line;
while (getline(cin, line)) {
// 将字符串分割成单词
vector<string> words;
istringstream ss(line);
string word;
while (ss >> word) {
words.push_back(word);
}
// 统计单词出现次数
for (auto& word : words) {
wordCount[word]++;
}
}
// 打印单词及其出现次数
for (auto& pair : wordCount) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
2. 电话簿管理系统
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// 创建map容器存储联系人信息
map<string, string> phoneBook;
// 添加联系人
phoneBook["John Doe"] = "123-456-7890";
phoneBook["Jane Smith"] = "234-567-8901";
phoneBook["Michael Jones"] = "345-678-9012";
// 查找联系人
string name;
cout << "Enter a name to search for: ";
cin >> name;
auto it = phoneBook.find(name);
if (it != phoneBook.end()) {
cout << "Phone number: " << it->second << endl;
} else {
cout << "Contact not found." << endl;
}
return 0;
}
结语
map容器是C++标准库中常用的关联式容器,它以键值对的形式存储数据,提供快速查找和检索的功能。map容器的使用方法简单,并且具有广泛的应用场景。