C++常用STL总结(应对CSP、蓝桥杯)_蓝桥杯常用的stl
常用的语法
万能头文件 #include
1.哈希表
暂时没用到
2.栈
特点:先进后出
用法
stack s;s.push(); 压栈/进栈s.pop(); 栈顶元素出栈(无返回值)s.top(); 返回栈顶元素s.empty(); 判断栈是否为空,是返回trues.size(); 返回栈中元素数量
3.for(char c : s)
相当于
for(int i =0;i <s.length(); i++ ){ }
但是会复制s这个字符串,然后进行遍历操作
在Java中,s是一个数组
4.队列
特点:先进先出/后进后出
# include//使用pushqueue q;q.push(\"Hello World\");q.push(\"hhh\");//使用sizeq.size() //返回2//使用front()、back()q.front() //返回\"Hello World!\'\'q.back() //返回最后一个 //pop()弹出q.pop();priotiry_queue Q;
5.Vector
#includevector vec;int a;vec.push_back(a);vec.size();vec.pop_back();for(vector::iterator it=obj.begin();it !=obj.end();it++) { cout<<*it<<\",\"; }
6.unordered_map
没有顺序而言,通过键值访问
#includeunordered_map um1;unordered_mao um2={{\"张三\",2}};//使用insert和pair插入um1.insert(pair(\"张三\",3));um1.insert({\"里斯\",5}) //可省略pairum1[\"里斯\"]++; //若没有里斯则创建一个。 //通过键值访问cout<first; value=it->second;}//用first和second
7.next_permutation()获取全排列
#includeint a[4] = {1,3,4,5};sort(a,a+a.size());//升序排序do{ for(int i=0;i<a.size();i++){ cout<< a[i]<<\" \"; } cout << endl;}while(next_permutation(a,a+a.size()));/*输出如下1 2 3 41 2 4 31 3 2 41 3 4 21 4 2 31 4 3 22 1 3 42 1 4 32 3 1 42 3 4 12 4 1 32 4 3 13 1 2 43 1 4 23 2 1 43 2 4 13 4 1 23 4 2 14 1 2 34 1 3 24 2 1 34 2 3 14 3 1 24 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个字符chs.replace(p0,n0,str); //删除从p0开始的n0个字符,然后在p0处插入字符串str//添加s.append(n,ch);s.append(str);//赋值s.assign(n,ch); //将n个ch赋值给ss.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[0],s2[0]); //仅交换第一个字符//反转reverse(s.begin(),s.end());//数值转化 (sto)to_string(val) //将val转化为stringstoi(str,pos,b); //将字符串s从p位置转化为b进制的int//查找string str = \"The apple thinks apple is delicious\"; //长度34string 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);查询出现次数//可用于vectorint a = count(vec.begin(),vec.end(),4);//reverse(iterator beg,iterator end); 反转//replace(iterator beg,iterator end,oldvalue,newvalue);替换元素