#include <stdio.h>
#include <map>
#include <xtree>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
multimap<int, int> mmap;
mmap.insert(pair<int, int>(1, 1));
mmap.insert(pair<int, int>(1, 2));
mmap.insert(pair<int, int>(2, 3));
multimap<int, int>::iterator iter = mmap.begin();
for (; iter != mmap.end(); ++iter)
printf("%d, %d\n", iter->first, iter->second);
//查找指定key的元素方法一:
multimap<int, int>::iterator iter_lower_bound = mmap.lower_bound(1);
multimap<int, int>::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<multimap<int, int>::iterator, multimap<int, int>::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 <stdio.h>
#include <map>
#include <xtree>
#include <algorithm>
using namespace std;
struct GreaterComp : public binary_function<const int&, const int&, bool>
{
result_type operator()(first_argument_type _Left, second_argument_type& _Right)
{
return _Left > _Right;
}
};
int main(int argc, char** argv)
{
multimap<int, int, GreaterComp> mmap;
mmap.insert(pair<int, int>(4, 3));
mmap.insert(pair<int, int>(4, 3));
mmap.insert(pair<int, int>(5, 3));
mmap.insert(pair<int, int>(2, 3));
mmap.insert(pair<int, int>(1, 1));
mmap.insert(pair<int, int>(1, 2));
mmap.insert(pair<int, int>(1, 5));
mmap.insert(pair<int, int>(2, 3));
multimap<int, int, GreaterComp>::iterator iter = mmap.begin();
for (; iter != mmap.end(); ++iter)
printf("%d, %d\n", iter->first, iter->second);
printf("\n");
//查找指定key的元素方法一:
multimap<int, int, GreaterComp>::iterator iter_lower_bound = mmap.lower_bound(1);
multimap<int, int, GreaterComp>::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<multimap<int, int, GreaterComp>::iterator, multimap<int, int, GreaterComp>::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
可以发现,操作是没什么不同的