c++ map 示例
map
is a container that stores elements in key-value pairs. It's similar to collections in Java, associative arrays in PHP, or objects in JavaScript.
map
是一个以键值对形式存储元素的容器。 它类似于Java中的集合,PHP中的关联数组或JavaScript中的对象。
Here are the main benefits of using map
:
这是使用map
的主要好处:
map
only stores unique keys, and the keys themselves are in sorted ordermap
仅存储唯一键,并且键本身按排序顺序- Because the keys are already in order, searching for an element is very fast 因为键已经按顺序排列,所以搜索元素非常快
- There is only one value for every key 每个键只有一个值
Here is an example:
这是一个例子:
#include <iostream>
#include <map>
using namespace std;
int main (){
map<char,int> first;
//initializing
first['a']=10;
first['b']=20;
first['c']=30;
first['d']=40;
map<char, int>::iterator it;
for(it=first.begin(); it!=first.end(); ++it){
cout << it->first << " => " << it->second << '\n';
}
return 0;
}
Output:
输出:
a => 10
b => 20
c => 30
d => 40
创建map
对象 (Creating a map
object)
map<string, int> myMap;
map<string, int> myMap;
插入 (Insertion)
Inserting data with insert member function.
使用插入成员函数插入数据。
myMap.insert(make_pair("earth", 1));
myMap.insert(make_pair("moon", 2));
We can also insert data in std::map using operator [] i.e.
我们还可以使用运算符[]将数据插入std :: map中,即
myMap["sun"] = 3;
myMap["sun"] = 3;
访问map
元素 (Accessing map
elements)
To access map elements, you have to create iterator for it. Here is an example as stated before.
要访问地图元素,您必须为其创建迭代器。 这是前面所述的示例。
map<char, int>::iterator it;
for(it=first.begin(); it!=first.end(); ++it){
cout << it->first << " => " << it->second << '\n';
}
翻译自: https://www.freecodecamp.org/news/c-plus-plus-map-explained-with-examples/
c++ map 示例