mapの常用用法

24838 ワード

mapはマッピングとして翻訳され、一般的なSTLコンテナでもあり、任意の基本タイプを任意の基本タイプにマッピングすることができます.
=#include==ヘッダファイルを追加する必要があります.
定義#テイギ#
map<typename1,typename2>mp;

1つ目はキーのタイプ、2つ目は値のタイプです.
注:文字列から整数へのマッピングの場合は、char配列ではなくstringを使用する必要があります.
コンテナ内の要素へのアクセス
1.下付きアクセス
注意:mapのキーは一意です.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['c']=20;
	mp['c']=30;//20   
	cout<<mp['c']; 
	return 0;
 } 

2.反復アクセス
map::iterator it;

実際、mapはit->firstを使用してキーにアクセスし、it->secondを使用して値にアクセスできます.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}

注意:map内部は赤黒ツリーで実現され(setも)、マッピングの確立中に小さいものから大きいものへの配列が自動的に実現されます.
map常用関数のインスタンス解析
1.find()
find(key)はキーがkeyのマッピングの反復器を返し,時間複雑度はO(logn),Nはmapでマッピングされた個数である.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	map<char,int>::iterator it=mp.find('r');
	cout<<it->first<<" "<<it->second<<endl;
	return 0;
}

2.erace()
(1)個々の要素の削除
mp.erase(it)
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	map<char,int>::iterator it=mp.find('r');
	mp.erase(it);//  r 30
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}

mp.erase(key)
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	//map::iterator it=mp.find('r');
	mp.erase('r');
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}

(3)区間内のすべての要素を削除する
mp.erase(first,last)は、左閉右開の区間[first,last]を削除する.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	map<char,int>::iterator it=mp.find('m');
	mp.erase(it,mp.end());//   r 30 m 20 
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}

(4)size()
sizeはmapにマッピングされた対数を得るために用いられ,時間複雑度はO(1)であった.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	/*map::iterator it=mp.find('m');
	mp.erase(it,mp.end());//   r 30 m 20 
	for(map::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<first<second<
	cout<<mp.size(); 
	return 0;
}

(4)clear()
clearはmap内のすべての要素をクリアするために使用され、複雑度はO(N)であり、Nはmap内の要素の個数である.
#include
#include
using namespace std;
int main()
{
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	/*map::iterator it=mp.find('m');
	mp.erase(it,mp.end());//   r 30 m 20 
	for(map::iterator it=mp.begin();it!=mp.end();it++)
	{
		cout<first<second<
	mp.clear();
	cout<<mp.size(); 
	return 0;
}

mapの一般的な用途
  • 文字(または文字列)と整数とのマッピングのテーマを確立する必要があります.mapを使用するとコード量を減らすことができます.
  • 大整数または他のタイプのデータが存在するか否かを判断する問題はmapをbool配列として用いることができる.
  • 文字列と文字列のマッピングも使用される場合があります.