25
2012
10

linux下练习 c++ 关联式容器共性测试,使用

code:

/*
关联式容器共性:二叉查找树实现,自动根据关键字排序,自动平衡
  set<K>,multiset<K>,map<K,V>,multimap<K,V>
查找:.find(key) 失败返回.end()
统计:.count(key)
删除:.erase(key)
插入:.insert(element)
区间:.lower_bund(key) //取得关键字为key的第一个元素位置
 .upper_bound(key) //取得关键字为key的最后一个元素之后的位置
 .equal_range(key) 取得关键字为key的区间,返回pair
构造函数可用比较函数作为参数  bool func(K a,K b)
*/
#include<iostream>
#include<set>
#include<string>
using namespace std;
#include "print.h"
struct person
{
string name;
int age;
public:
person(const char* n,int a):name(n),age(a){}
};
bool operator<(const person& a,const person& b)
{
return a.age<b.age||(a.age==b.age&& a.name<b.name);//找的时候按这个找
}
ostream& operator<<(ostream& o,const person& x)
{
return o<<x.name<<':'<<x.age<<"  ";
}
int main()
{
multiset<person> mp;
mp.insert(person("ccc",16));
mp.insert(person("aaa",13));
mp.insert(person("aaa",13));
mp.insert(person("kkk",18));
mp.insert(person("fff",15));
mp.insert(person("eee",11));
mp.insert(person("jjj",16));
print(mp.begin(),mp.end());
multiset<person>::iterator it=mp.find(person("fff",15));
if(it==mp.end()) cout<<"not find!\n";
else
{
 cout<<"find:"<<*it
         <<" "<<mp.count(*it)<<"个\n";
}
person a("aaa",13);
cout<<a<<" "<<mp.count(a)<<"个\n";
cout<<"lower/upper bound方法:\n";
multiset<person>::iterator ibegin,iend;
ibegin=mp.lower_bound(a);
iend=mp.upper_bound(a);
print(ibegin,iend);
cout<<"pair方法:\n";
typedef multiset<person>::iterator myiter;//给长类型起个别名
pair<myiter,myiter> p=mp.equal_range(a);
print(p.first,p.second);
cout<<"删除后输出:\n";
mp.erase(person("kkk",18));//有多个就删除多个
print(mp.begin(),mp.end());
}


结果:



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。