STL不全
2025-08-30 15:32:24
发布于:上海
STL容器:
1.set:集合
1.没有重复的元素
2.自动排序:
//插入元素(自动去重)
s.insert(x) x =1 , 4 , 3;
s = { 1 , 3 , 4 }
3.打印:迭代器
for(set<int>::iterator it = s.begin();it != s.end(); it++){
cout << *it << endl;
}
或者用 auto :
for(auto it = s.begin(); it != s.end() ; it++){
cout << *it << endl;
}
/*
在指针中:
* 为解地址符
& 为取地址符
*/
相当于指针:
int a = 10;
int *a1 = & a;//int* 为指针类型
a -> 10 -> 0x3f
a1 -> 0x3f -> 0x4f
4.实用小工具:
find : O(log n)查找
auto it = s.find(1);
// 存在返回值是地址
//若不存在这个数返回end()
if(s.find(x) == s.end()){//s.end()为 s 中最后一个数的下一个位置
cout<<"No"<<endl;
}
2,list:链表
优势:便于插入删除操作 O(1)插入
劣势 : 查找非常慢 O(n) 查找
1.插入
list<int> L;
L.push_front(x);//头插 :在头节点的后面插入一个x
L.push_back(x);//尾插 : 在尾节点的后面插入一个x
2.遍历查找:迭代器
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
//迭代器:
for(list<int>::iterator it = l.begin(); it != l.end(); it ++)
//auto代替:
for(auto it = l.begin(); it != l.end() ; it++){
cout << *it << endl;
}
3,删除
//用find找到要删除的数据的地址
auto k = find(l.begin() , l.end() , 1);
//再用erase删除
l.erase(k);
4,去重
//将重复的删除并返回删除后的最后一个元素下标
a[6] = {1,1,2,2,3};
cout << unique(a , a + 5) - a;//返回 3
这里空空如也
有帮助,赞一个