C++stl-map/multimap容器概念以及用法
map基本概念:
簡介:
map中所有元素都是pair
pair中第一個元素為key(鍵值),起到索引作用,第二個元素為value(實值)
所有元素都會根據元素的鍵值自動排序
本質:
map/multimap屬于關聯式容器,底層結構是用二叉樹實作
優點:
可以根據key值快速找到value值
map和multimap差別:
map不允許容器中有重複key值元素
multimap允許容器中有重複值key值元素
map構造和指派
功能描述:
對map容器進行構造和指派操作
函數原型:
構造:
map<T1, T2>mp; //map預設構造函數
map(const map &mp); //拷貝構造函數
指派:
代碼示例:
#include<iostream>
#include<map>
using namespace std;
//map容器 構造和指派
void printMap(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key=" << (*it).first << " value=" << it->second << endl;
}
cout << endl;
}
void test01()
{
//建立map容器
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 20));
m.insert(pair<int, int>(3, 30));
m.insert(pair<int, int>(4, 40));
printMap(m);
//拷貝構造
map<int, int>m2(m);
printMap(m2);
//指派
map<int, int>m3;
m3 = m2;
printMap(m3);
}
int main()
{
test01();
system("pause");
return 0;
}
總結:map中所有元素都是成對出現,插入資料時候要使用對組。