梦见你的名字 发表于 2025-4-2 01:29:16

C++常用STL总结(应对CSP、蓝桥杯)

常用的语法

万能头文件 #include<bits/stdc++.h>
1.哈希表

暂时没用到
2.栈

特点:先辈后出
用法

stack<type>  s;
s.push(); 压栈/进栈
s.pop(); 栈顶元素出栈(无返回值)
s.top(); 返回栈顶元素
s.empty(); 判断栈是否为空,是返回true
s.size(); 返回栈中元素数量
3.for(char c : s)

相当于
for(int i =0;i <s.length(); i++ ){
   
} 但是会复制s这个字符串,然后进行遍历操纵
在Java中,s是一个数组
4.队列

<queue>
特点:先辈先出/后进后出
# include<queue>

//使用push
queue<string> q;
q.push("Hello World");
q.push("hhh");

//使用size
q.size()   //返回2

//使用front()、back()
q.front() //返回"Hello World!''
q.back() //返回最后一个
   
//pop()弹出
q.pop();

priotiry_queue<int> Q;
​ 5.Vector

#include<vector>

vector<int> vec;
int a;

vec.push_back(a);
vec.size();
vec.pop_back();


for(vector<int>::iterator it=obj.begin();it !=obj.end();it++)

{
   cout<<*it<<",";

}
6.unordered_map

没有顺序而言,通过键值访问
#include<unordered_map>

unordered_map<string,int> um1;
unordered_mao<string,int> um2={{"张三",2}};


//使用insert和pair插入
um1.insert(pair<string,int>("张三",3));
um1.insert({"里斯",5})   //可省略pair

um1["里斯"]++;    //若没有里斯则创建一个。
   
//通过键值访问
cout<<um1["张三"];

//遍历
for(auto it=Map.begin();it!=Map.end();++it){
   Key=it->first;
   value=it->second;
}

//用first和second

7.next_permutation()获取全排列

#include<algorithm>

int a = {1,3,4,5};
sort(a,a+a.size());//升序排序

do{
    for(int i=0;i<a.size();i++){
      cout<< a<<" ";
    }
    cout << endl;
}while(next_permutation(a,a+a.size()));

/*输出如下
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
*/ 8.String

string s1 = "abc";
string s2 = "def";
cout << s1.length(); //长度
//插入
s.insert(pos,n,ch);
s.insert(pos,str);
//替换
s.replace(p0,n0,n,ch); //删除从p0开始的n0个字符,然后在p0处插入n个字符ch
s.replace(p0,n0,str);  //删除从p0开始的n0个字符,然后在p0处插入字符串str

//添加
s.append(n,ch);
s.append(str);

//赋值
s.assign(n,ch); //将n个ch赋值给s
s.assign(str);
s.assign(str,pos,n);//将str从pos位置开始的n个字符给s
   
//删除
s.erase(pos,n); //从pos开始的n个字符

//剪切
s = s.substr(pos,n);
s = s.substr(pos); //从pos到结束

//比较
s1.compare(s2); //返回1 -1 0

//交换
swap(s1,s2);
swap(s1,s2);   //仅交换第一个字符

//反转
reverse(s.begin(),s.end());

//数值转化 (sto)
to_string(val) //将val转化为string
stoi(str,pos,b); //将字符串s从p位置转化为b进制的int

//查找
string str = "The apple thinks apple is delicious";     //长度34
string key = "apple";

s.find(str); //返回str在s中第一次出现的位置
s.find(ch);
s.find(str,pos);
s.rfind();//从后往前找
int pos = str.find(key);   // 4 常用stl

//count(iterator beg,iterator end,value);查询出现次数
//可用于vector
int a  = count(vec.begin(),vec.end(),4);


//reverse(iterator beg,iterator end); 反转

//replace(iterator beg,iterator end,oldvalue,newvalue);替换元素


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: C++常用STL总结(应对CSP、蓝桥杯)