C++ STL - vector map string algorithm 常用操作

<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;
    }
}
//输出:
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>算法

  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的个数
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值