C++语法总结

Vector

//head file
#include<vector>

//define & init
vector<int> a;
vector<int> a(3);//size =3
vector<int> a(3,1);//size=3 ,all elements' val=1
vector<int> b(a);// same as vector a
vector<int> c(a.begin(),a.begin()+3)//size=3,if a={1,2,3,4,5},then c={1,2,3}
//P.S this is different with vector<int> a(3,1


//init with arr
int a[]={1,2,3,4};
vector b(a,a+2);//b's elements: 1,2

// 2-D vector
vector<vector<int>> a(10,vector<int>(5,1))// 10*5 ,init with 1

//basic op
a.size();
a.empty();
a.clear();
b.erase(b.begin(),b.begin()+2);//earse 2 elments from the begin 
b.insert(b.begin(),3,100);//insert 3 elements(val=100) from the begin
b.swap(a);
a.push_back();//insert to the end
a.pop_back();//pop the last one
a.back();//return the last one
a.front();//retunr the first one
a.end();//return the one after the last one

String

string s="hello world";
string s2("hello world");

int length1=s.length();
int length2=s.size();
int length3 = strlen(s.c_str());//因为strlen是对char*用的,所以要先转换为char*

algorithm

#include<algorithm>
#include<cmath>
int a=5,b=-3;
float c=-1.5;
int max_v=max(a,b);
int min_v=min(a,b);
int abs_v=abs(b);//for integer
int abs_f=fabs(c);// for float ,double in cmath

优先级队列

#include <queue>
priority_queue<int> q; //从大到小出
priority_queue<int,vector<int>,less<int> > q; //同上
priority_queue<int,vector<int>,greater<int> > q; //从小到大出,P.S 最后那个> 要空一格,不然就成右移操作了

// greater也可以自定义,就像比较大小的函数,定义一个cmp,并传入
priority_queue<int,vector<int>,cmp> q;

//还可以定义结构体
//比如定义二叉树常用的一个node
priority_queue<node> q;

//basic op
q.empty();
q.size();
q.top();
q.pop();
q.push();

#pair

//pair用于表示一种关联关系,key-value
//define
pair<string,int> p;
p.first='hello';
p.second=2;

pair<string,int> q1('world',3);
make_pair<string,int>('test',4);

长度

//strlen(const char *__s)
char c[10]="aaaaaaaa";
cout<<strlen(c)<<endl;//8

char* d="bbbbb";
cout<<strlen(d)<<endl;//5

 int a[]={1,2,3};
// cout<strlen(a)<<endl; //error
cout<<sizeof(a)/sizeof(a[0]);//3



//string中的length(),size()是一样的
string str="aaaaa";
cout<<str.length()<<endl;//5
cout<<str.size()<<endl;//5

//char arr
char* d="bbbbb";
cout<<sizeof(d)<<endl;//8 , d is the pointer,sizeof(d) means the size of the pointer
cout<<sizeof(*d)<<endl;//1 , the size of the first char

char D[]="aaaabbbbb";
cout<<sizeof(D)<<endl;//10
cout<<sizeof(*D)<<endl;//1

char D[50]="aaaabbbbb";
cout<<sizeof(D)<<endl;//50
cout<<sizeof(*D)<<endl;//1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值