cpp-map

map内部本身就是按序存储的(比如红黑树)。在我们插入<key, value>键值对时,就会按照key的大小顺序进行存储。这也是作为key的类型必须能够进行<运算比较的原因。

#include <map>
map<int, int> mapCode;
for (int i = 0; i < m_pDb->m_vResult.size(); i += 2)
{
mapCode.insert(std::pair<int, int>(m_pDb->m_vResult.at(i + 1).typeInt64, m_pDb->m_vResult.at(i).typeInt64));
}

Searches the container for elements with a key equivalent to k and returns the number of matches.
Because all elements in a map container are unique, the function can only return 1 (if the element is found) or zero (otherwise).
if ( 0 < g_mapHookInfo.count(hWnd))
{
//present
HOOKINFO hookInfo = g_mapHookInfo[hWnd];
if (hookInfo.type == type)
{
return 0; // already hooked!
}
}

赋值 [] insert 区别

insert 操作:如果key存在,则插入失败,如果key不存在,就创建这个key-value。实例: map.insert((key, value))
[] 操作符:如果这个key存在,就更新value;如果key不存在,就创建这个key-value对 实例:map[key] = value

// assume m is std::map<int,int> already has an element with key 5 and value 0
m[5] = 10; // postcondition: m[5] == 10
m.insert(std::make_pair(5,15)); // m[5] is still 10

sort


删除元素

map<int,string*> m;
m[1]= new string("1111111111111111");
m[2]= new string("2222222222222222");
m[3]= new string("3333333333333333");
m[4]= new string("4444444444444444");
m[0]= new string("5555555555555555");
map<int,string*>::iterator it;
for(it=m.begin();it!=m.end();)
{
cout<<"key: "<<it->first <<" value: "<<*it->second<<endl;
delete it->second;
m.erase(it++);
}

遍历

// 清理掉属于该类的实例信息
for (auto& it = pwnd->m_curInfo.mapBusiInstInfo.begin(); it != pwnd->m_curInfo.mapBusiInstInfo.end();)
{
if (it->second["classHid"].asInt64() == classHid)
{
pwnd->m_curInfo.mapBusiInstInfo.erase(it++);
}
else
{
++it;
}
}

for (auto&it: g_pMain->m_CodeInfo)
{
wstring ss = it->first.c_str();
int iTmp = it->second;
}

key是否存在

if (m_curInfo.mapMonitorInfo.count(str))
{
//exist
}
else
{
//not exist. should be a new file
}

const map<wstring, wstring>& filter
auto search = filter.find(fileName);
if (search == filter.end())
{
//not found, can be delete
if (FALSE == DeleteFile(it.c_str()))
{
//delete file faild.
iRet = -1;
}
}

复制