数组容器:缺点:插入,删除,比较麻烦
1.array
静态数组,在栈上,不可变长,适用于数量小的
2.vector
动态数组,在堆上,可变长,适用数量大的
链表容器:查找比较快
3.list 链式存储
不允许下标访问,只能用迭代器访问
list.clear()//清空
erase();//删除操作
push_back();//后插
push_front();//前插
insert(地址,值);//
begin();end()//正向遍历
rbegin();rend();//反向遍历
ls.sort();
ls.unique();//删除相同相,之前必须先排序才有效
ls.merge(ls2)//归并,把ls2归并到ls里去,归并前要先排序
红黑树容器
红黑树容器:增删查改都比较快
处理纯数字很少见,常用于处理类对象和字符串
4.set //缺点,不能包含同一个值
inset();//每次插入一个数据都会重新排序,
对字符串的操作
struct strless
{
bool operator()(const char *str1,const char* str2)
{
return strcmp(str1,str2)<0;
}
}
void main()>
const char * string[] = {"add","xyy","qwd","ffgdf","sfsdf"};
set<const char *, strless> myset(string,string+5,strless());
pair<set<const char*,strless>::iterator,bool>pr= myset.insert("24324");//pair获取插入返回值
printf("*pr=%s\n",*pr.first);
printf("bool=%d\n", pr.second);
map,mutlimap区别是map每一个节点是一个映射
multimap每一个一个节点是映射的链表的开头(mulitimap的每个节点是链表)
5.map
struct class_stu
{
char *name;
int year;
};
struct infoid
{
int id;
class_stu stu;
};
void main_map1()
{
infoid info[3] = { { 101, { "xyy", 1994 } }, { 102, { "txj", 1994 } }, { 103, {"zzz",1995} } };
map<int, class_stu> mymap;
for (int i = 0; i < 3; i++)
{
mymap[info[i].id] = info[i].stu;//每个ID映射到每个学生信息
}
map<int, class_stu>::iterator ib = mymap.begin();
map<int, class_stu>::iterator ie = mymap.end();
for (; ib != ie; ib++)
{
cout << (*ib).first << " " << (*ib).second.name << " " << (*ib).second .year<< endl;
}
cin.get();
}
5.2multimap
void main_map2()
{
infoid info[3] = { { 101, { "xyy", 1994 } }, { 102, { "txj", 1994 } }, { 103, { "zzz", 1995 } } };
multimap<int, class_stu> mymap;
for (int i = 0; i < 3; i++)
{
mymap.insert(pair < int, class_stu>(info[i].id,info[i].stu));//每个ID映射到每个学生信息
}
infoid info2 = { 101, {"aaa",1998} };
mymap.insert(pair < int, class_stu>(103, info2.stu));
multimap<int, class_stu>::iterator ib = mymap.begin();
multimap<int, class_stu>::iterator ie = mymap.end();
for (; ib != ie; ib++)
{
cout << (*ib).first << " " << (*ib).second.name << " " << (*ib).second.year << endl;
}
cin.get();
}
用hash表实现秒插
6hash_set
void main_hash_set()
{
hash_set<const char *>hs;
hs.insert("1asfsd");
hs.insert("2asfsd");
hs.insert("3asfsd");
hs.insert("4asfsd");
hs.insert("5asfsd");
auto ib = hs.begin();
auto ie = hs.end();
for (; ib != ie; ib++)
{
cout << *(ib) << " " << endl;
}
auto tofind = hs.find("3asfsd");
if (tofind == ie)
{
cout << "没找到" << endl;
}
else
{
cout << *(tofind) << endl;
}
cin.get();
}
7hash_map不自动排序
map自动排序
void main()
{
hash_map< int,const char *>mymap;
mymap[10] = "司令";
mymap[9] = "军长";
mymap[7] = "团长";
mymap[8] = "旅长";
mymap.insert(pair< int,const char *>(5, "营长"));
auto ib = mymap.begin();
auto ie = mymap.end();
for (; ib != ie; ib++)
{
cout << (*ib).first << " " << (*ib).second << endl;
}
cin.get();
}