#include #include #include #include using namespace std; int main(int argc, char** argv) { multimap mmap; mmap.insert(pair(1, 1)); mmap.insert(pair(1, 2)); mmap.insert(pair(2, 3)); multimap::iterator iter = mmap.begin(); for (; iter != mmap.end(); ++iter) printf("%d, %d\n", iter->first, iter->second); //查找指定key的元素方法一: multimap::iterator iter_lower_bound = mmap.lower_bound(1); multimap::iterator iter_upper_bound = mmap.upper_bound(1); for (; iter_lower_bound != iter_upper_bound; iter_lower_bound++) printf("%d, %d\n", iter_lower_bound->first, iter_lower_bound->second); //查找指定key的元素方法二: iter = mmap.find(1); int num = mmap.count(1); int k = 0; for (; iter != mmap.end() && k < num; iter++, k++) printf("%d, %d\n", iter->first, iter->second); //查找指定key的元素方法三: pair::iterator, multimap::iterator> p_ret = mmap.equal_range(1); while (p_ret.first != p_ret.second) { printf("%d, %d\n", p_ret.first->first, p_ret.first->second); p_ret.first++; } getchar(); return 0; }
运行结果为:
1, 1 1, 2 2, 3 1, 1 1, 2 1, 1 1, 2 1, 1 1, 2
如果键是降序排列的话
#include #include #include #include using namespace std; struct GreaterComp : public binary_function { result_type operator()(first_argument_type _Left, second_argument_type& _Right) { return _Left > _Right; } }; int main(int argc, char** argv) { multimap mmap; mmap.insert(pair(4, 3)); mmap.insert(pair(4, 3)); mmap.insert(pair(5, 3)); mmap.insert(pair(2, 3)); mmap.insert(pair(1, 1)); mmap.insert(pair(1, 2)); mmap.insert(pair(1, 5)); mmap.insert(pair(2, 3)); multimap::iterator iter = mmap.begin(); for (; iter != mmap.end(); ++iter) printf("%d, %d\n", iter->first, iter->second); printf("\n"); //查找指定key的元素方法一: multimap::iterator iter_lower_bound = mmap.lower_bound(1); multimap::iterator iter_upper_bound = mmap.upper_bound(1); for (; iter_lower_bound != iter_upper_bound; iter_lower_bound++) printf("%d, %d\n", iter_lower_bound->first, iter_lower_bound->second); printf("\n"); //查找指定key的元素方法二: iter = mmap.find(1); int num = mmap.count(1); int k = 0; for (; iter != mmap.end() && k < num; iter++, k++) printf("%d, %d\n", iter->first, iter->second); printf("\n"); //查找指定key的元素方法三: pair::iterator, multimap::iterator> p_ret = mmap.equal_range(1); while (p_ret.first != p_ret.second) { printf("%d, %d\n", p_ret.first->first, p_ret.first->second); p_ret.first++; } printf("\n"); getchar(); return 0; }
5, 3 4, 3 4, 3 2, 3 2, 3 1, 1 1, 2 1, 5 1, 1 1, 2 1, 5 1, 1 1, 2 1, 5 1, 1 1, 2 1, 5