c++ 在multimap中查找关键字的程序举例
生活随笔
收集整理的這篇文章主要介紹了
c++ 在multimap中查找关键字的程序举例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在文件example.cc中有如下關于m1的定義:
//文件example.cc #include <string> #include <iostream> #include <map> using namespace std; multimap<string,int> m1{{"str1",1},{"str1",2},{"str1",3},{"str1",4},{"str1",5},{"str1",6}};現在來查找m1中關鍵字等于"str1"的值分別是多少.
方法1:
#include <string> #include <iostream> #include <map> #include "example.cc" using namespace std; int main() { multimap<string,int>::iterator it = m1.find("str1"); int cnt = m1.count("str1"); int i = 0; for(i = 0;i != cnt; ++i){cout << it->second << endl;it ++;}方法2:
#include <string> #include <iostream> #include <set> #include <map> #include "example.cc" using namespace std; int main() { multimap<string,int>::iterator it; for(it = m1.lower_bound("str1");it != m1.upper_bound("str1"); ++ it)cout << it->second << endl;方法3:
#include <iostream> #include <string> #include <map> #include "example.cc" int main() { pair<multimap<string,int>::iterator,multimap<string,int>::iterator> p = m1.equal_range("str1"); for(auto it = p.first; it != p.second; ++it)cout << it->second << endl;return 0; } ~說明:(1)以上方法upper_bound和lower_bound函數不適用于無序容器。(打個比方,就好比是沒有順序的數列就沒有位置的區分了)
? ? ? ? ? ? ?(2)在有序關聯容器中,關鍵字相同的元素總是連續存儲的。
總結
以上是生活随笔為你收集整理的c++ 在multimap中查找关键字的程序举例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何关闭uefi启动模式|预装win8/
- 下一篇: string中删除一个元素