<vector>
声明定义
vector<int> v(5)
声明长度为5的vector,并且初始化为0vector<int> v={1,2,3,3,2,1}声明初始值为{1,2,3,3,2,1}
的vector,长度为6
常用方法
v.size()
返回vector长度(包含的有效值个数)v[0]
可用方括号访问特定位置的值,v[v.size()-1]=0
并且可以修改特定位置的值,但是不能访问或更改超出size()范围的值v.clear()
清空vector,并且size()长度变为0v.push_back(0)
在vector尾端插入值
<map>
声明定义
map<int,int> m
m的每个值类型是pair<int,int>
常用方法
typedef pair<int,int> Pair
m.insert(Pair(1,2))
map插入数据m.size()
map有效值个数m[1]
可以方括号(键)来访问和修改相对应的值,注意如果如果访问不存在的键,map会自动把该键和0值存入(仅限int类型,其他类型值会为空),如下图例子
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
typedef pair<int, int> Pair;
int main(){
map<int,int> m;
m.insert(Pair(1,-9));
cout<<m[2]<<endl;
for(auto x:m){
cout<<x.first<<" "<<x.second<<endl;
}
}
//输出:
0
1 -9
2 0
<string>
string基本操作
string str="helloworld";
str[1]='E';//可以用方括号访问和修改string的值
string与int类型互相转换
string str="123";
char* ch=str.c_str();//string先转化成char*
int in=atoi(ch);//atoi接受char*类型参数并转化成int
注意:如果字符串开头没有数字,则atoi会转化成0,否则会转化开头到第一个不为数字的字符之前的数字,实例如下:
char* c1="hello123"//atoi(c1)会输出0
char* c2="123hello"//atoi(c2)会输出123
int转string用另一种方法
#include <sstream>
int in=123;
stringstream ss;
ss<<in;
string str=in.str();
string方法
str.find('c',pos=0)//搜索字符,默认从pos=0处搜索
str.find("str",pos=0)//搜素字符串,默认从pos=0处搜索,可以是string类也可以是char*类字符串
<algorithm>
算法
sort(v.begin(),v.end())
&sort(v.begin(),v.end(),function)
count(v.begin(),v.end(),0)
查找等于0的个数
count_if(v.begin(),v.end(),function)
查找function返回true的个数