C++ STL相关库应用实例

文章目录
  1. 1. vector
    1. 1.1. 使用vector创建一个二维数组
    2. 1.2. vector数据的存入,输出与清空
    3. 1.3. 使用vector对map数据根据下标或者value排序
  2. 2. set
    1. 2.1. set遍历
  3. 3. string
    1. 3.1. string 的基本操作
  4. 4. C++输出对应的精度的小数

鉴于最近在练习一些C++相关的字符串类型的题目,STL工具库里面的很多东西不是很熟练,所以写一篇博客来记录一些算法考试中常用的C++ STL库的用法。

vector

vector是一个动态数组,不需要声明数组大小,可以直接往里面添加元素或者直接删除元素。

使用vector创建一个二维数组

创建格式

1
vector<vector<数据类型>> 名称(二维数组行数);

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
int main()
{
int n=3;//确定的行数
vector<vector<LL>> v(n);
for(int i=0;i<n;i++)
v[i].resize(4);
for(int i=0;i<n;i++)
for(int j=0;j<5;j++)
v[i][j]=6;
for(int i=0;i<n;i++)
{
for(int j=0;j<5;j++)
cout<<v[i][j]<<" ";
cout<<endl;
}

return 0;
}

vector数据的存入,输出与清空

数据存入

1
2
vector<int>vec;
vec.push_back();//括号里为放入的数据

数据输出有两种
(1)数组下标访问

1
2
for(int i=0;i<vec.size();i++)
cout<<vec[i]<<endl;

(2)指针访问

1
2
for(vector<int>::iterator iter=vec.begin();iter!=vec.end();iter++)
cout<<iter<<endl;

数据清空

1
vec.clear();

使用vector对map数据根据下标或者value排序

1
2
3
4
5
6
typedef pair<int,int>PAIR;
map<int,int>m;
//省略中间存入值的过程
vector<PAIR>vec(m.begin(),m.end());
sort(vec.begin(),vec.end(),cmp);
//cmp是自定义排序

上面那个太简陋了…直接看下面这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
#define maxn 999999
typedef pair<int,int>PAIR;
map<int,int>a;
bool cmp(pair<int,int>x,pair<int,int>y)
{
return x.second>y.second;
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int x;
cin>>x;
a[x]+=1;
}
vector<PAIR>vec(a.begin(),a.end());
sort(vec.begin(),vec.end(),cmp);
cout<<vec[0].first<<endl;
}
return 0;
}

set

写在最前,set的数据类型不包括long long,这个用得比较少,后面用到了会继续更新。

set遍历

set遍历需要使用迭代器,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<cstdio>
#include <vector>
#include <set>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
int main()
{
set<int> valid;
valid.insert(15);
valid.insert(18);
for(set<int>::iterator it=valid.begin();it!=valid.end();it++)
cout<<*it<<endl;
return 0;
}

string

string比起char来说要更直接,更方便,可以不用设置字符串的长度,直接输入,直接拼接。

string 的基本操作

获取字符串长度

1
string.size();

字符串拼接

1
2
3
4
5
6
7
string str1;
cin>>str1;
string str2;
cin>>str2;
string str;
str=str1+str2;
cout<<str<<endl;

字符串其中一个字符替换,这里比如替换最后一个字符;

1
2
3
string str="abcdefg";
str[str.size()-1]="k";
cout<<str<<endl;

C++输出对应的精度的小数

需要在输出的小数前加上fixed和setprecision(),其中括号里是小数精度。

1
cout<<fixed<<setprecision(9)<<vec[i]<<endl;