C++ map 详解:用法、示例和应用场景
C++ 中的'map'是一个关联容器,它提供了一种映射关系,可以将键和值进行关联。下面是'map'的常见用法和示例:
- 插入元素:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> map;
// 使用insert()函数插入元素
map.insert(std::make_pair(1, 'apple'));
map.insert(std::make_pair(2, 'banana'));
map.insert(std::make_pair(3, 'orange'));
// 使用下标运算符[]插入元素
map[4] = 'grape';
return 0;
}
- 查找元素:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> map;
map.insert(std::make_pair(1, 'apple'));
map.insert(std::make_pair(2, 'banana'));
map.insert(std::make_pair(3, 'orange'));
// 使用find()函数查找元素
auto it = map.find(2);
if (it != map.end()) {
std::cout << 'Value found: ' << it->second << std::endl;
} else {
std::cout << 'Value not found' << std::endl;
}
// 使用count()函数检查元素是否存在
if (map.count(3) > 0) {
std::cout << 'Value exists' << std::endl;
} else {
std::cout << 'Value does not exist' << std::endl;
}
return 0;
}
- 访问元素:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> map;
map.insert(std::make_pair(1, 'apple'));
map.insert(std::make_pair(2, 'banana'));
map.insert(std::make_pair(3, 'orange'));
// 使用下标运算符[]访问元素
std::cout << 'Value at key 2: ' << map[2] << std::endl;
// 使用迭代器访问元素
for (auto it = map.begin(); it != map.end(); ++it) {
std::cout << 'Key: ' << it->first << ', Value: ' << it->second << std::endl;
}
return 0;
}
- 删除元素:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> map;
map.insert(std::make_pair(1, 'apple'));
map.insert(std::make_pair(2, 'banana'));
map.insert(std::make_pair(3, 'orange'));
// 使用erase()函数删除元素
map.erase(2);
// 使用迭代器删除元素
auto it = map.find(3);
if (it != map.end()) {
map.erase(it);
}
return 0;
}
这些只是'map'的一些常见用法和示例,还有其他更多的用法和函数可以根据实际需要进行探索和使用。
原文地址: http://www.cveoy.top/t/topic/qaqo 著作权归作者所有。请勿转载和采集!