STL标准库之Map和Vector
1. 首先明确Map是通过(<Key,Value>)Key来存储Value的值,Key可以是C语言的所有类型,Value也是任意类型,今天我就来说说Map与Vector的基本使用。(数据结构如下图)
1. 头文件里面写上要存放一组数据的结构体:
structInfoStruct
{
wxString m_TimeInfo;
wxString m_StateInfo;
wxString m_TimeLenInfo;
};
2. 在类中定义全局变量map和结构体变量
typedefstd::map <long , std::vector<InfoStruct>* > mapInfo;
mapInfo mapinfo;
InfoStructinfostruct;
3. 在cpp文件中把数据一组一组的存入到map里面
infostruct.m_StateInfo= TranState(sub); //把状态里面的值赋值给结构体m_StateInfo
infostruct.m_TimeInfo = getCurrentTime(); //把收到消息的当前时间赋给结构体里面的m_TimeInfo
std::vector <InfoStruct> * vectinfo =NULL;
std::map<long ,std::vector<InfoStruct>* >::iterator iter = mapinfo.find(id); //定义查找Key的迭代器
if(iter != mapinfo.end()) //判断Key是否存在
{
vectinfo = iter->second; //把map存储value的
vectinfo->push_back(infostruct);
iter->second = vectinfo;
}
else
{
vectinfo = newstd::vector<InfoStruct>; //定义vector向量的指针变量,申请内存空间
vectinfo->push_back(infostruct); //把结构体放到vector里面
mapinfo.insert(std::make_pair(id,vectinfo));
}
4. 读取map里面的数据
itemIndex1=itemListCtrlTemp->GetNextItem(itemIndex1,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);
if(itemIndex1 == -1)
{
break;
}
wxString str1 =GetContentsString(itemIndex1,0,itemListCtrlTemp);
wxString str2 =GetContentsString(itemIndex1,1,itemListCtrlTemp);
wxString str3 = GetContentsString(itemIndex1,2,itemListCtrlTemp);
wxString str4 =GetContentsString(itemIndex1,5,itemListCtrlTemp);
static_Text->SetLabel(_("通道:" +str1 + str2 + str3 + str4));
std::vector<InfoStruct> *vectinfo1 = NULL;
long findIndex = wxAtoi(str1) * 16 * 16+ wxAtoi(str2) * 16 + wxAtoi(str3);
std::map<long ,std::vector<InfoStruct>* >::iterator iter1 = mapinfo.find(findIndex);
if(iter1 != mapinfo.end())
{
vectinfo1 = iter1->second;
std::vector <InfoStruct>::iteratorvectIter1;
for(vectIter1 =vectinfo1->begin() ;vectIter1 != vectinfo1->end(); vectIter1++)
{
long index =itemListCtrlState->InsertItem(0,vectIter1->m_TimeInfo,0);
itemListCtrlState->SetItem(index,1,vectIter1->m_StateInfo);
}
}
}
更多详细学习在这里,给大家总结里许多自己在工作中的问题,也许您也能遇到!