1. 程式人生 > >c++中如何關聯兩個變數的值-鍵值對,c++map的使用

c++中如何關聯兩個變數的值-鍵值對,c++map的使用

在開發的場景中會用到將無關的值關聯起來,後面會根據一個值來查詢、使用其相對應的值,這裡鍵值對是一個不錯的選擇,即使用c++map的特性實現這一簡單功能。

map是一類關聯式容器,增加和刪除節點對迭代器的影響很小。除了對操作節點有影響,對其他的節點沒有什麼影響。map主要建立了key到value的對映。key和value可以是任意型別。

注意:對於迭代器來說,可以修改實值,而不能修改key。

根據key值快速查詢記錄,查詢的複雜度基本是Log(N),如果有1000個記錄,最多查詢10次。 

快速插入Key - Value 記錄。 

快速刪除記錄 

根據Key 修改value記錄。 

遍歷所有記錄。 

使用過程:

#include <map>

map<key,value>     key-first,   value-second

為了使用方便,可以對模板類進行一下型別定義,

typedef map<int, CString> DEFINEMAP;

DEFINEMAP myMap;

插入map元素:

改變map中的條目非常簡單,因為map類已經對[]操作符進行了過載

myMap[1] = "One";

myMap[2] = "Two";

這樣非常直觀,但存在一個性能的問題。插入2時,先在myMap中查詢主鍵為2的項,沒發現,然後將一個新的物件插入my

Map,鍵是2,值是一個空字串,插入完成後,將字串賦為"Two"; 該方法會將每個值都賦為預設值,然後再賦為顯示的值,如果元素是類物件,則開銷比較大。我們可以用以下方法來避免開銷:

myMap.insert(map<int, CString> :: value_type(2, "Two"))

查詢並獲取map中的元素

下標操作符給出了獲得一個值的最簡單方法:

CString tmp = enumMap[2];

但是,只有當map中有這個鍵的例項時才對,否則會自動插入一個例項,值為初始化值。

查詢函式:Find(key)和Count()。

begin()和end()兩個成員,分別代表map物件中第一個條目和最後一個條目,這兩個資料的型別是iterator

int nFindKey = 2; //要查詢的Key

//定義一個條目變數(實際是指標)

myMap::iterator it= enumMap.find(nFindKey);

if(it == enumMap.end()) {

//沒找到

}

else {

//找到

}

通過map物件的方法獲取的iterator資料型別是一個std::pair物件。

iterator包括兩個資料 iterator->first 和 iterator->second 分別代表關鍵字key和儲存的資料value。

從map中刪除元素

移除某個map中某個條目用erase(),注意引數是條目iterator

該成員方法的定義如下

iterator erase(iterator it):通過一個條目it物件刪除 

iterator erase(iterator first, iterator last):刪除一個範圍 [first,end]裡面的元素

size_type erase(const Key& key):通過關鍵字key刪除 

clear():刪除所有元素

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的函式

例子:

//遍歷:

map<string,CAgent>::iterator iter;
 for(iter = m_AgentClients.begin(); iter != m_AgentClients.end(); ++iter)
 {
   if(iter->first=="8001"  {
     this->SendMsg(iter->second.pSocket,strMsg);//iter->first
   }
 }

//查詢:

map<string,CAgent>::iterator iter=m_AgentClients.find(strAgentName);
 if(iter!=m_AgentClients.end())//有重名的  {
 }
 else //沒有{
 }

//元素的個數

if (m_AgentClients.size()==0)

//刪除

map<string,CAgent>::iterator iter=m_AgentClients.find(pSocket->GetName());
 if(iter!=m_AgentClients.end())
 {

     m_AgentClients.erase(iter);//列表移除
 }


#include <iostream>
#include <map>
#include <string>

using namespace std;

void map_insert(map<string,string> *mapStudent, string index, string x){
	mapStudent->insert(map<string,string>::value_type(index,x));
}

int main(){
	char tmp[32]="";
	map<string, string> mapS;
	map_insert(&mapS,"192.168.0.128","xiong");
	map_insert(&mapS,"192.168.200.3","feng");
	map_insert(&mapS,"192.168.200.33","xiongfeng");
	
	map<string, string>::iterator iter;
	
	cout<<"we have there elements"<<endl;
	cout<<"----------------------"<<endl;
	
	
	iter=mapS.find("192.168.200.33");
	
	//查詢 
	cout<<"查詢"<<endl; 
	if(iter!=mapS.end()){
		cout<<"find the element"<<endl;
		cout<<"it is:"<<iter->second<<endl;		
	}else{
		cout<<"not find the element"<<endl;
	}
	
	//遍歷
	cout<<"遍歷"<<endl; 
	for(iter=mapS.begin();iter!=mapS.end();iter++){
		cout<<"| "<<iter->first<<" | "<<iter->second<<" |"<<endl;
	} 
	
	//刪除
	cout<<"刪除"<<endl;  
	iter=mapS.find("192.168.200.33");
	if(iter!=mapS.end()){
		cout<<"find the element"<<endl;
		cout<<"delete the element"<<endl;
		mapS.erase(iter);
	}else{		
		cout<<"not find the element"<<endl;
	}
	
	for(iter=mapS.begin();iter!=mapS.end();iter++){
		cout<<"| "<<iter->first<<" | "<<iter->second<<" |"<<endl;
	} 
	return 0;
}