C++竞赛常用函数库stl快捷查询手册(vector,map,set,queue,string等)

发布时间 2023-04-07 22:55:34作者: 神雨临
1.控制输出流<iomanip>;
  1. cout<<setprecision(< span="">int);保留int位有效数字
  2. cout<<setprecision(< span="">int)<<fixed;保留int位有效小数
  3. 为不足4位数的数填充0(如1填充变成0001), cout<<setfill('0')<<setw(4) (一次性效果)
 1 #include<iostream>
 2 #include<iomanip>
 3 using namespace std;
 4 int main()
 5 {
 6 double a = 335.34224, b = -0.0000587689, e = 12.0;
 7 int c = 234934;
 8 cout << c << endl;
 9 cout << setiosflags(ios::showbase|ios::hex|ios::showpos);//显示基数,按16进制,显示正号
10 cout << c << endl;//由于没有终止10进制显示,故16无法生效;
11 cout << resetiosflags(ios::dec);//终止功能函数
12 cout << c << endl;
13 cout << setiosflags(ios::uppercase);//字母大写
14 cout << c << endl<<endl;
15 
16 cout << resetiosflags(ios::showbase | ios::showpos|ios::uppercase|ios::hex);
17 
18 cout << e << endl;
19 cout << setiosflags(ios::showpoint);//显示小数点并显示默认6位有效数字
20 cout << e << endl << a << endl << b << endl;
21 cout << setiosflags(ios::fixed);//显示默认6位小数点后数字
22 cout << a<<endl ;
23 cout << resetiosflags(ios::fixed);
24 cout << a << endl;
25 cout << setprecision(4)<<setiosflags(ios::scientific|ios::left)<<resetiosflags(ios::right);//显示4位有效数字,使用科学计数法,使用左对齐,终止右对齐
26 cout << setw(20)<<setfill('*');//设置输出宽度为20,填充字符为*
27 cout << a << endl<<endl;
28 }

 

 
2.<string>的常用用法(待补充);
1.查找指定字符 str.find("6"),返回字符‘6’第一次出现的位置下标,否则返回-1;
2.getchar()获取字符。
3.int m=a.compare(b);逐字符比较字符串的ascii码,若小于则返回 -1大于返回1,等于返回0.
可以设置多个参数和比较指定字符串区间.
3.C++标准程序库STL其他常用函数;
  1. sort(数组名,结束地址,排序规则);其中greater()为大到小,不写为默认小到大.
  2. memset(name,value,sizeof()); 为标识符名为name的数据赋大小为value的值,空间单位为sizeof(name).
 
4<map>.容器,特点:键值key只允许出现一次,一个键值对应一个数据
  1. map<key,val> mp; 定义一个关联式容器mp:
  2. mp.insert(pair<int,string>(int1,"str1")); 为mp插入元素
  3. int i1=11; np[i1]="a11"; 为np插入元素
  4. mp.count(key) ;
查看键值key是否存在|返回键为key的元素个数(返回0或1)
// 使用count()方法
if (my_map.count(2)) { // 如果存在键为2的元素
std::cout << "Key 2 exists in the map." << std::endl;
} else {
std::cout << "Key 2 does not exist in the map." << std::endl;
}
  1. auto a1=mp.find(123);需要使用迭代器auto来对map进行查找操作,如果找到了则返回对应key值,如果没找到则返回mp.end();(注意auto只支持C++11以上)
  2. map<int,string>::iterator it1=np.find(33);迭代器查找2
  3. for (map<int, string="">::iterator it = np.begin(); it != np.end(); it++)
cout << it->first<<" "<second;
5.<queue>容器 特点:内含优先队列priority_queue可以自动堆排列数组
  1. priority_queueq1;创建int型优先队列(堆)
  2. q1.push(x);将x加入队列
  3. q1.pop();删除队首元素
  4. q1.top();取出队首元素
  5. q1.size();返回元素数量
  6. priority_queue<pair<int,int> >q2;创建一个<int,int>型优先队列(堆)
  7. q2.push({x,y});将{x,y}加入队列
  8. q2.top().second;取出一组队首元素中的第二个元素
6.<vector>容器,特点:自助动态数组
  1. vector v1;创建1维vector v1
  2. vector<vector > v2;创建2维vector v2
  3. v1.push_back(1);尾部插入 | v2.push_back(v1);为2维数组尾部插入数组v1
  4. v1.empty();判断v1是否为空
  5. v1.clear();清楚v1中的元素
  6. v1.size();返回v1中元素的个数
 
7.<set>容器,特点:自动从小到大排序并且元素唯一
  1. sets<int> s; 定义
  2. s.insert(x); 插入元素
  3. s.empty(); 判断是否为空
  4. set::iterator it; for(it=s.begin();it != s.end(); it++) cout<<*it; ; 利用迭代器遍历