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/
- 下一篇: c++ primer 5th 练习11.