C++ STL

来源:互联网 发布:99直播软件下载 编辑:程序博客网 时间:2024/05/22 08:03

<vector>

声明定义

  1. vector<int> v(5)声明长度为5的vector,并且初始化为0
  2. vector<int> v={1,2,3,3,2,1}声明初始值为{1,2,3,3,2,1}的vector,长度为6

常用方法

  1. v.size()返回vector长度(包含的有效值个数)
  2. v[0]可用方括号访问特定位置的值,v[v.size()-1]=0并且可以修改特定位置的值,但是不能访问或更改超出size()范围的值
  3. v.clear()清空vector,并且size()长度变为0
  4. v.push_back(0)在vector尾端插入值

<map>

声明定义

  1. map<int,int> m m的每个值类型是pair<int,int>

常用方法

  1. typedef pair<int,int> Pair
    m.insert(Pair(1,2))map插入数据
  2. m.size()map有效值个数
  3. 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;    }}//输出:01 -92 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)会输出0char* 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>算法

  1. sort(v.begin(),v.end()) &sort(v.begin(),v.end(),function)
  2. count(v.begin(),v.end(),0)查找等于0的个数
    count_if(v.begin(),v.end(),function)查找function返回true的个数