C++
从 C++98 到 C++20,寻觅甜甜的语法糖们
c++ enable_if 的简单使用
语法
struct, class中可以直接用外面的变量- 自定义比较器:
struct cmp {
bool operator () (int x,int y) const
{ return h[x] < h[y]; }
}; priority_queue<int,vector<int>,cmp> pq;
- 如何用new来创建二维数组
- 输出详细调试信息:
#ifdef FS
#define debug(x) cerr<<__FUNCTION__<<"() line"<<__LINE__<<" : "<<#x" = "<<(x)<<endl;
#else
#define debug void()
#endif
auto
auto up = [&](int u) { t[u]=t[ls(u)]+t[rs(u)]; }; 可以当函数用,且只在局部有效
algorithm
lower/upper_bound
lower: 大于等于
upper: 大于
要求:“升序”(可重载运算符)
用法:lower_bound(begin, end, x); 在
时间复杂度:
// 数组a
int *p = lower_bound(a+l, a+r+1, x);
int q = lower_bound(a+l, a+r+1, x) - a;
// 查询[l,r]。此时q-1为小于x的最大值的下标
// STL容器:返回迭代器
set<int,int> s;
auto it = s.lower_bound(x);
vector<int> vec;
it = lower_bound(vec.begin(), vec.end(), x);
// upper_bound 同理
sort
sort(begin(),end(),cmp) 为将左闭右开区间按比较函数 cmp (需满足严格弱序)排序,默认为升序。对于 int 等第三个参数可传 greater<int>() 来变成降序。
stable_sort 稳定快排
merge
merge(l1,r1,l2,r2,p,cmp) 将 [l1,r1) 和 [l2,r2) 中的元素按 cmp 归并排序,首元素在 p
inplace_merge(l,mid,r,cmp) 原地归并排序 [l,mid) 和 [mid,r)
时间复杂度:
nth_element
nth_element(a+l,a+k,a+r+1,cmp) 可以找到
find_if
find_if(begin,end,[&](int j){return check(i,j);}) 返回在
fill
fill(begin,end,x) 给
cctype
isspace(x):x 是否是空格/Tab/换行
cstdio
scanf("%1d",&a); 读入一位数字(1 可改)
printf("%02d,a); 输出2(可改)位数 a,若不够则高位补 0(可改,若不写则补空格)
printf("%0*d",w,a); w 位,其余同上
cstring
memset
int
0x7f: 2139062143(memset 能赋的最大值)
0x3f: 1061109567(memset 能赋且两倍在 int 范围内的最大值)
0: 0
0xff: -1
0xcf: -808464433
0x80: -2139062144
iostream
输出与输入位数相同的小数:cin cout
读入一行(带空格)到字符串:cin.getline(s,len)(len为长度上限)
swap(a,b):
-
a,b$ 为数组:$O(sizeof\ a)
iterator
prev,next
map
unordered_map
卡到
queue
priority_queue
重载运算符
set
定义:
pair<iterator,bool> insert(const val_type& val)
iterator erase(const_iterator first,const_iterator last)
边遍历边删除:
for(auto it = s.begin(); it != it.end(); )
it = s.erase(it);
multiset count 操作复杂度
string
in/out
ios::sync_with_stdio(false);cin.tie(0); // 加速cin(不可与stdio混用)
cin>>s;
cout<<s;
s.clear();while(isalpha(c=getchar()))s+=c;
读入一行(带空格):getline(s,len)
库函数
// string1 + string2 : 将string2接到string1后面
s.substr(l,len); // 返回s的字串[l,l+len) l的默认值为0,len为s.size()-l
s.insert(p,ss); // 在s的第p个字符前插入字符串ss
s.find(ss); // 返回ss在s中第一次出现时首字母下标;没有则返回-1或一个比s.size()大的数
s.find(ss,pos); // 从下标pos开始
stoi(s) // 返回s表示的int(stoul,stoll 同理)
vector
函数
vec.assign(n,x):清空 vec 并将 vec[0..n-1] 赋值为
vec.erase(remove(itl,itr,x)):删除
vec.shrink_to_fit(); 释放 vec 多余的内存
指针
传参
int a[N],b[N][N];
void do1(int x[]) { return; } // 或 int *x
void do2(int x[][N]) { return; }
int main() {
do1(a), do2(b);
}