在程序中map的簡單使用方法——續

在前一篇是關於map的簡單使用。接下來,說下查找功能。
由於map機制是一一對應關係,一個key對應一個value,不允許重複的key對應不同的value,所以其默認查找方式是以key爲索引進行查找定位;
在網上可以找到常用的方法,主要是find以及[]操作符;

map< int , DWORD > mapAll;
map< int, DWORD>::iterator map_it;
mapAll.find(key);
DWORD dwVal = mapAll[key];
那麼如果要根據value進行查找呢,則需要用到
#include <map>//STL頭文件,不用添加.h  用於map容器使用
#include <algorithm>//
添加這兩個文件先,用到裏面的
find_if函數,不過由於find_if的第三個參數有特別需求,所以主要記錄下這個的用法。
我的代碼
class map_value_finder
{
public:
map_value_finder(const DWORD &cmp_info):m_s_cmp_info(cmp_info){}
bool operator ()(const map<int,DWORD>::value_type &pair)
{
return pair.second == m_s_cmp_info;
}
private:
const DWORD &m_s_cmp_info;                    
};
不過此處的private變量是根據之前map定義的類型進行變化的,如我的
map< int , DWORD >

const DWORD &m_s_cmp_info;   
對應,若是改成
map< int , string >
那麼對應的
const string &m_s_cmp_info;同時, 構造函數
map_value_finder(const DWORD &cmp_info):m_s_cmp_info(cmp_info){}
也得改成
map_value_finder(const string &cmp_info):m_s_cmp_info(cmp_info){}
基本使用就是這個了。
程序中使用方法
map_it = find_if(mapAllChannel.begin(),mapAllChannel.end(),map_value_finder(nZone|nCh));
if (map_it == mapAllChannel.end())
{//說明未找到}
else
...










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章