C++|STL学习笔记-map的属性(大小以及是否存在)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/84132336

目录

1.size()的用法

2.多多使用count(xxx)进行判断


1.size()的用法

map的property

map属性
1.没有容量;
2.得到元素的个数size()

这里给出调用他size()的例子,源码如下:

/************************************************************************/
/* map property                                                         */
/************************************************************************/

#include <map>
#include <iostream>
#include <algorithm>
using namespace std;


typedef pair<int, char> in_pair;
typedef pair<map<int, char>::iterator, bool> in_pair_bool;

void judgeOk(in_pair_bool pr){
	if(pr.second){
		cout << "insert the success!" << endl;
	}
	else{
		cout << "insert the failture!" << endl;
	}
}

void mapProperty(){
	map<int, char> mp;
	pair<map<int, char>::iterator, bool> pr;

	pr = mp.insert(in_pair(1, 'a'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'b'));
	judgeOk(pr);
	pr = mp.insert(in_pair(3, 'c'));
	judgeOk(pr);
	pr = mp.insert(in_pair(4, 'd'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'e'));
	judgeOk(pr);

	cout << "The map size is " << mp.size() << endl;
}

void main(){

	mapProperty();

	getchar();
}

运行截图如下:

2.多多使用count(xxx)进行判断

这里有个小知识点使用count判断map是否存在,不存在返回0

个人感觉STL中map的这一点就没有QTL好用了,

QTL是这样的命名:

是不是感觉QTL更加通俗易懂:

下面给出STL中关于count的栗子:

/************************************************************************/
/* map property                                                         */
/************************************************************************/

#include <map>
#include <iostream>
#include <algorithm>
using namespace std;


typedef pair<int, char> in_pair;
typedef pair<map<int, char>::iterator, bool> in_pair_bool;

void judgeOk(in_pair_bool pr){
	if(pr.second){
		cout << "insert the success!" << endl;
	}
	else{
		cout << "insert the failture!" << endl;
	}
}

void mapProperty(){
	map<int, char> mp;
	pair<map<int, char>::iterator, bool> pr;

	pr = mp.insert(in_pair(1, 'a'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'b'));
	judgeOk(pr);
	pr = mp.insert(in_pair(3, 'c'));
	judgeOk(pr);
	pr = mp.insert(in_pair(4, 'd'));
	judgeOk(pr);
	pr = mp.insert(in_pair(2, 'e'));
	judgeOk(pr);

	cout << "The map size is " << mp.size() << endl;
	
	cout << "The use of count() function" << endl;
	if(mp.count(3)){
		cout << "presence key three" << endl;
	}

	map<int, char>::iterator it = mp.begin();
	for(it; it != mp.end(); it++){

		cout << it->first << "\t" << it->second << endl;
	
	}

}

void main(){

	mapProperty();

	getchar();
}

运行截图如下:

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/84132336