c ++中stl
Maps are associative containers. Maps store elements in form of apair of key value and there mapped value and the key value are stored in sorted manner. Maps are a part of the C++ STL and key values in maps are generally used to identify the elements i.e. there is a value associated with every key. Therefore, there are no two elements in map which have same key and internally, the elements in a map are always sorted by its key. The type of key and elements can be differ in map.
地图是关联容器。 映射以一对键值的形式存储元素,并且映射后的值和键值按排序方式存储。 映射是C ++ STL的一部分,并且映射中的键值通常用于标识元素,即每个键都有一个关联的值。 因此,映射中没有两个元素具有相同的键,并且在内部,映射中的元素始终按其键排序。 键和元素的类型在地图中可以不同。
Map Template:
地图模板:
std::map <key_type, data_type>
Syntax of declaration:
声明语法:
map <key_type,data_type> myMap;
This line creates a map myMap, where key is of type specified by key_type and element is of type specified by data_type.
此行创建一个地图myMap ,其中key是key_type指定的类型,而element是data_type指定的类型。
Now, explore some built in function used in map:
现在,探索一些用于map的内置函数 :
Functions | Description |
---|---|
begin() | It returns an iterator to the first element |
end() | It returns an iterator to the element which is just after to the last element |
size() | It returns the number of elements in the map |
empty() | It returns whether the map is empty or not |
clear() | It removes all the elements from the map |
pair insert(key_value,map_value) | It insert a new element to the map |
erase(iterator position) | It erase the element at the position pointed by the iterator |
功能 | 描述 |
---|---|
开始() | 它将迭代器返回到第一个元素 |
结束() | 它向元素的迭代器返回迭代器,该迭代器紧随最后一个元素 |
尺寸() | 它返回地图中的元素数 |
空() | 它返回地图是否为空 |
明确() | 它将所有元素从地图中删除 |
对insert(key_value,map_value) | 它将新元素插入地图 |
擦除(重复位置) | 它在迭代器指向的位置擦除元素 |
Example:
例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
map <int, string> mymap;
// insert elements in map
mymap.insert(pair <int, string> (1, "include"));
mymap.insert(pair <int, string> (2, "help"));
mymap.insert(pair <int, string> (3, "computer"));
mymap.insert(pair <int, string> (4, "science"));
mymap.insert(pair <int, string> (5, "portal"));
// printing map elements
map <int, string> :: iterator it;
cout<<"Elements in map : "<<endl;
for (it = mymap.begin(); it != mymap.end(); it++)
{
cout <<"key = "<< it->first <<" value = "<< it->second <<endl;
}
//erase element having key = 1
mymap.erase(1);
cout<<"Elements in map after erasing element having key = 1 : "<<endl;
for (it = mymap.begin(); it != mymap.end(); it++)
{
cout <<"key = "<< it->first <<" value = "<< it->second <<endl;
}
return 0;
}
Output
输出量
Elements in map :
key = 1 value = include
key = 2 value = help
key = 3 value = computer
key = 4 value = science
key = 5 value = portal
Elements in map after erasing element having key = 1 :
key = 2 value = help
key = 3 value = computer
key = 4 value = science
key = 5 value = portal
c ++中stl