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