日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++中不得不說的map容器_C 語言

作者:獨取一瓢C++ ? 更新時間: 2022-04-16 編程語言

前言

為什么這兩天在研究C++的容器呢,因為刷題的時候碰見了幾個不擅長的題,得用STL中的幾種容器才能解出來,所以也是動力滿滿呀,希望能盡快轉過頭去把那幾個題給寫出來,哈哈哈,當然,解題思路和過程后續我也會分享出來。話不多說,老規矩,

使用map容器要包含頭文件#include<map>

1,map基本概念

簡介:

? map中所有元素都是pair(成對出現的數)

? pair中第一個元素為key(鍵值),起到索引的作用,第二個元素為value(實值)

? 所有的元素都會根據元素的鍵值自動排序

本質:

? map/multimap屬于關聯式容器,底層結構是用二叉樹實現的

優點

? 可以根據key值快速找到value值

map和multimap的區別:

? map不允許容器中有重復的key值元素

? multimap允許容器中有重復的key值元素

2,map構造和賦值

功能描述:?

? 對map容器進行構造和賦值操作

代碼實現:

#include<iostream>
#include<map>
using namespace std;
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容器 1,默認構造
	map<int, int>m;  //要寫兩個數據類型
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(3, 30));  //與插入的順序無關
	m.insert(pair<int, int>(2, 20));  //容器會根據key值進行自動排序
	m.insert(pair<int, int>(4, 40));
	printMap(m);
 
	//2,拷貝構造
	map<int, int>m2(m);
	printMap(m2);
 
	//3,賦值
	map<int, int>m3;
	m3 = m2;  //等號方式賦值
	printMap(m3);
}
int main() {
	test01();
	return 0;
}

3,大小和交換

功能描述:

?? 統計map容器大小以及交換map容器

函數原型:

size(); //返回容器中元素的個數

empty(); //bool類型,判斷容器是否為空

swap(st); //交換兩個集合容器

4,插入和刪除

功能描述:

? map容器進行插入和刪除數據

代碼實現:

#include<iostream>
#include<map>
using namespace std;
void test01()
{
	map<int, int>m;  
	//第一種插入
	m.insert(pair<int, int>(1, 10));
	
	//第二種插入
	m.insert(make_pair(2, 20)); //不用寫模板參數
 
	//第三種插入
	m.insert(map<int, int>::value_type(3, 30));
 
	//第四種插入
	m[4] = 40;
 
	//第一種刪除
	m.erase(m.begin()); //參數為迭代器
 
	//第二種刪除
	m.erase(1); //按照key刪除
 
	//第三種刪除
	m.erase(m.begin(), m.end()); //區間刪除
 
	//第四種刪除
	m.clear(); //全部刪除
}
int main() {
	test01();
	return 0;
}

5,查找和統計

功能描述:

? 對map容器進行查找數據以及統計數據

函數原型:

? find(key);

/*查找key是否存在,若存在,返回該元素的迭代器;

若不存在,返回end()迭代器*/

? count(key);???? // 統計key的元素個數

/*map不允許插入重復key值,count統計結果要么是0,要么是1

multimap的count統計結果可能大于1*/

6,排序

? map容器默認的排序方式是,按照key值進行從小到大的排序,但是我們可以利用仿函數實現從大到小排序,話不多說,直接上代碼

#include<iostream>
#include<map>
using namespace std;
class MyCompare
{
public:
	bool operator()(int v1,int v2)const
	{
		return v1 > v2;  //降序
	}
};
void test01()
{
	map<int, int, MyCompare>m;  //加入仿函數
	m.insert(make_pair(1, 10)); 
	m.insert(make_pair(2, 20));
	m.insert(make_pair(3, 30));
	m.insert(make_pair(4, 40));
	for (map<int, int,MyCompare>::iterator it = m.begin(); it != m.end(); it++) {//輸出的時候別忘了加上
		cout << "key=" << it->first << " value=" << it-> second << endl;
	}
}
int main() {
	test01();
	return 0;
}

另外,對于自定義數據類型,map必須要指定排序規則。

總結

原文鏈接:https://blog.csdn.net/m0_63134260/article/details/122851188

欄目分類
最近更新