標籤:
Map是c++的一個標準容器,她提供了很好一對一的關係,在一些程式中建立一個map可以起到事半功倍的效果,總結了一些map基本簡單實用的操作!
1. map最基本的建構函式;
map<string , int >mapstring; map<int ,string >mapint;
map<sring, char>mapstring; map< char ,string>mapchar;
map<char ,int>mapchar; map<int ,char >mapint;
2. map添加資料;
map<int ,string> maplive;
1.maplive.insert(pair<int,string>(102,"aclive"));
2.maplive.insert(map<int,string>::value_type(321,"hai"));
3, maplive[112]="April";//map中最簡單最常用的插入添加!
3,map中元素的尋找:
find()函數返回一個迭代器指向索引值為key的元素,如果沒找到就返回指向map尾部的迭代器。
map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else cout<<"wo find 112"<<endl;
4,map中元素的刪除:
如果刪除112;
map<int ,string >::iterator l_it;;
l_it=maplive.find(112);
if(l_it==maplive.end())
cout<<"we do not find 112"<<endl;
else maplive.erase(l_it); //delete 112;
map的基本操作函數:
C++ Maps是一種關聯式容器,包含“關鍵字/值”對
begin() 返回指向map頭部的迭代器
clear() 刪除所有元素
count() 返回指定元素出現的次數
empty() 如果map為空白則返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊條目的迭代器對
erase() 刪除一個元素
find() 尋找一個元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比較元素key的函數
lower_bound() 返回索引值>=給定元素的第一個位置
max_size() 返回可以容納的最大元素個數
rbegin() 返回一個指向map尾部的逆向迭代器
rend() 返回一個指向map頭部的逆向迭代器
size() 返回map中元素的個數
swap() 交換兩個map
upper_bound() 返回索引值>給定元素的第一個位置
value_comp() 返回比較元素value的函數
程式碼範例:
#include <iostream>#include <map>#include <set>#include <string>#include <vector>using namespace std;int main(){ map< string, int > mapForTest; mapForTest.insert( pair<string, int>( "jim", 67 ) ); mapForTest.insert( make_pair( "john", 85 ) ); mapForTest[ "jack" ] = 95; mapForTest[ "lily" ] = 96; cout << "Using iterator\n"; map< string, int >::iterator it = mapForTest.begin(); while( it != mapForTest.end() ) { cout << it->first << " => " << it->second << endl; it ++; } cout << "Using reverse_iterator\n"; map<string, int>::reverse_iterator reit = mapForTest.rbegin(); while( reit != mapForTest.rend() ) { cout << reit->first << " => " << reit->second << endl; reit ++; } cout << "Using [] to get the value\n"; cout << "lily got the score of " << mapForTest["lily"] << endl; string query_name; cout << "please input the name to query\n"; cin >> query_name; it = mapForTest.find( query_name ); if( it == mapForTest.end() ) cout << "there is no " << query_name << " in the database\n"; else cout << "Use find(): " << query_name << " got the score of " << it->second << endl; mapForTest.clear(); mapForTest.insert( make_pair( "tom", 89 ) ); mapForTest.insert( pair<string, int>( "kevin", 86 ) ); cout << "current size of mapForTest is: " << mapForTest.size() << endl; return 0;}
執行情況如下所示:
c++ map快速入門