C++ Map 通过GetNextAssoc()根据value找key


来自:https://blog.csdn.net/codingEMIPark/article/details/81566988?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

 

map可以用find根据key来找map,现实现一个简单在MFC中value为字符串的简单map查找。

  1.   short CLBMViewerView::findMAPKeyByValue(typedef CMap<unsigned short,unsigned short,CString,CString>& map,char* c)
  2.  {
  3.       unsigned short key;
  4.      CString str;
  5.      POSITION pos = map.GetStartPosition();
  6.       while(pos!=NULL){
  7.           map.GetNextAssoc(pos,key,str);
  8.           if(strcmp(str,CString(c))==0)
  9.               return key;
  10.      }
  11.       return -1; //means no match key with value
  12.  }

其中POSITION是MFC模板类库中的一个数据类型,这里的作用类似于STL中的Iterator.

GetNextAssoc()的作用是取出当前迭代器位置的key和value,然后向后移动迭代器。

这里通过CString(c)直接将char *转为string,用strcmp比较取出的字符串与待寻找的字符串是否相同。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM