📜  map c++ (1)

📅  最后修改于: 2023-12-03 15:32:48.814000             🧑  作者: Mango

Map in C++

map is a container in C++ STL (Standard Template Library) that stores elements as key-value pairs. It is implemented as a self-balancing binary search tree (Red-Black Tree).

Syntax
map<key, value> map_variable;
Operations
Insertion

Elements can be inserted using the insert() or [] operator.

map<string, int> m;

// Using insert()
m.insert(make_pair("apple", 10));
m.insert(make_pair("banana", 20));

//Using []
m["cherry"] = 30;
Printing

Elements can be printed using iterators.

map<string, int>::iterator it;

for (it = m.begin(); it != m.end(); it++) {
    cout << it->first << ": " << it->second << endl;
}
Accessing Elements

Accessing elements can be done using the [] operator or the at() method.

map<string, int> m;

m["apple"] = 10;

int quantity = m["apple"];

cout << "Quantity of apples: " << quantity << endl;
Finding Elements

Elements can be found using the find() method.

map<string, int> m;

if (m.find("apple") != m.end()) {
    cout << "Apple found!" << endl;
}
else {
    cout << "Apple not found." << endl;
}
Deletion

Elements can be erased using the erase() method.

map<string, int> m;

m.erase("apple");
Size

The size of the map can be obtained using the size() method.

map<string, int> m;

int size = m.size();
Clear

All elements in the map can be cleared using the clear() method.

map<string, int> m;

m.clear();
Conclusion

map is a powerful and useful container in C++ STL. It provides a convenient way to store key-value pairs and perform operations on them.