C++のstd::mapの使い方は?
std::mapを使用するには、ヘッダーファイルを含める必要があります。std::mapは、ユニークなキーを持つキーと値のペアを格納するための連想コンテナです。
これはstd::mapの基本的な使用例です。
#include <iostream>
#include <map>
int main() {
// 创建一个std::map对象
std::map<int, std::string> students;
// 插入键值对
students.insert(std::make_pair(1, "Alice"));
students.insert(std::make_pair(2, "Bob"));
students.insert(std::make_pair(3, "Charlie"));
// 通过键访问值
std::cout << "Student with key 1: " << students[1] << std::endl;
// 修改值
students[2] = "Ben";
// 遍历std::map
std::cout << "All students:" << std::endl;
for (const auto& student : students) {
std::cout << "Key: " << student.first << ", Value: " << student.second << std::endl;
}
// 检查键是否存在
if (students.count(3) > 0) {
std::cout << "Student with key 3 exists" << std::endl;
}
// 删除键值对
students.erase(2);
return 0;
}
この例は、std::mapオブジェクトを作成する方法、キーと値を挿入する方法、値にアクセス・変更する方法、std::mapを繰り返し処理する方法、およびキーと値を削除する方法を示しています。なお、存在しないキーに[]演算子でアクセスすると、新しいキーと値が挿入されることに注意してください。
上記の例の出力は、〜する必要があります。
Student with key 1: Alice
All students:
Key: 1, Value: Alice
Key: 2, Value: Ben
Key: 3, Value: Charlie
Student with key 3 exists