C++中unordered_set和unordered_map的API示例:
#include <iostream>
#include <unordered_set>
#include <unordered_map>
int main() {
// unordered_set的API示例
std::unordered_set<int> mySet;
// 插入元素
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// 遍历集合
std::cout << "unordered_set elements:";
for (auto elem : mySet) {
std::cout << " " << elem;
}
std::cout << std::endl;
// 检查元素是否存在
std::cout << "Does mySet contain 20? " << (mySet.count(20) ? "Yes" : "No") << std::endl;
// 删除元素
mySet.erase(20);
// 遍历集合
std::cout << "unordered_set elements after erasing 20:";
for (auto elem : mySet) {
std::cout << " " << elem;
}
std::cout << std::endl;
// 清空集合
mySet.clear();
std::cout << "unordered_set size after clearing: " << mySet.size() << std::endl;
// unordered_map的API示例
std::unordered_map<int, std::string> myMap;
// 插入键值对
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
// 遍历map
std::cout << "unordered_map elements:";
for (const auto& pair : myMap) {
std::cout << " {" << pair.first << ": " << pair.second << "}";
}
std::cout << std::endl;
// 检查键是否存在
std::cout << "Does myMap contain key 2? " << (myMap.count(2) ? "Yes" : "No") << std::endl;
// 删除键值对
myMap.erase(2);
// 遍历map
std::cout << "unordered_map elements after erasing key 2:";
for (const auto& pair : myMap) {
std::cout << " {" << pair.first << ": " << pair.second << "}";
}
std::cout << std::endl;
// 清空map
myMap.clear();
std::cout << "unordered_map size after clearing: " << myMap.size() << std::endl;
return 0;
}
插入元素、删除元素、检查元素是否存在、遍历集合以及清空集合。