跳到正文

算法·理论

带你了解真正的 C++ & 卡常技巧

Super_Diu约 13 分钟
原文
文章信息与版本

文章信息

发布
2026年4月11日
收录
2026年4月11日
更新
2026年11月20日
篇幅
约 13 分钟

版本

  1. v2当前
  2. v1

C++,一个成千上万 OIer 都在用的语言。

你,真的了解它吗?

遇到 TLE 但是复杂度正确的代码,你,知道怎么卡过吗?

1. 特点

C++ 是一个通用、极高性能的编程语言,++ 的意思就是 C 语言 的增强版。

它最大的特点就是运行速度极快,秒杀 Python、Java 等主流语言。比喻一下你们就知道了:

  • Python:新手友好,开发快,但跑得慢(轿车);

  • Java:平衡易用性和性能(SUV);

  • C++:开发稍难,但跑得最快、能操控一切(F1)。

2. 各个版本

此处只展示洛谷中有的版本。

  • C++98:

    • 优点:平均运行速度最快(卡常用)。

    • 缺点:不安全(int* p=new int 之后,不 delete 或者 delete 两次都会崩溃)、几乎没有内存安全检查。

  • C++11:

    • 优点:大改 C++98,加入了 auto、基础的 Lambda 表达式和 nullptr 等好用的语法,C++ 也是在这个版本之后封神。

    • 缺点:不能自动推导类模板(pair<int,string> p={1,"abc"}; 不能写成 pair p={1,"abc"};)。

  • C++14:

    • 优点:兼实用性和性能,是 CSP、NOIP、NOI、ICPC / CCPC 等比赛的官方语言。

    • 缺点:没有结构化绑定(for(auto& [key,val]:map)),也不能自动推导类模板。

  • C++17:

    • 优点:前面说的所有缺点它都没有。

    • 缺点:几乎没有。

    • 本蒟蒻用的就是这个。

  • C++20:

    • 优点:适用于写工程。

    • 缺点:速度稍慢。

  • C++23:

    • 优点:加入了完全能替代 printf 和 cout 的新输出方法 std::print(),包含在头文件 print 中。

    • 缺点:没有及时更新万能头(bits/stdc++.h),只包含 C++17 及之前的稳定标准库,导致不包含头文件 print。速度较慢。

3. 编译指令

  • 基础:

    -std=c++(your version)。

    例如 -std=c++14、-std=c++17 之类的。

  • 基础警告:

    -std=c++(your version) -Wall。

    可以告诉你一些可能出错的地方(变量定义了但是没用、函数没写返回值、隐式类型转换等)。

  • 进阶警告:

    -std=c++(your version) -Wall -Wextra。

    告诉你很多经常犯的错(条件语句里 == 写成 =、函数参数未使用、指针和整数比较等,推荐使用)。

  • 优化:

    -std=c++(your version) -O(1~3 or s or fast)。

    O1 编译速度快,运行相比不加快一点。

    O2 编译速度快,运行快(推荐)。

    O3 编译速度慢,运行极快。

    Ofast 编译速度很慢,运行速度最快(最激进的优化,可能把浮点数的精度降低)。

    Os 编译速度慢,.exe 体积小。

注意:

-O2 -std=c++14 -Wall 也能运行。

-Wextra 没有 -Wall 的功能!要写就一起写。

本蒟蒻用的是 -std=c++17 -Wall -Wextra -O2。

4. 卡常技巧

这个应该是你们最想看的。

  1. 在 C++11 之前(不包括 C++11),用的频繁的变量前加上 register 会更快(例如 for(register int i=1;i<=n;++i))。优化为 5%5\% 到 10%10\%?

  2. ++i 比 i++ 稍微快一点(迭代器)。优化大约 2%2\%

  3. 函数前加上 inline 可能反而变慢。不同版本的编译器会有不同的效果。

  4. 用 cin 或 cout 的话,在主函数第一行加上 ios::sync_with_stdio(false),cin.tie(0) 或者 cin.tie(0)->sync_with_stdio(0)。输入输出快 1010 倍!

  5. endl 换成 '\n'。输出快 2∼52 \sim 5 倍。

  6. 变量尽量开全局。

  7. 多用按位计算(x%2==x&1,x/2==x>>1,x*2==x<<1,pow(2,x)==(1<<x))。加速 10%∼20%10\% \sim 20\%。

  8. 循环赋值(for 或 fill)尽量用 memset(只能精确赋值 00 和 −1-1)。快 33 倍左右。

  9. 复制数组用 memcpy(目标数组,原数组,sizeof 原数组)。快 55 倍。

  10. int 比 long long 快。速度优化很微小。

  11. 尽量别用万能头。比火车头多 3 ms3\ \text{ms} 左右。

  12. 八聚氧(洛谷不能用,本地可以):

C++
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")

快 55 倍。

  1. 超级整形快读(照样用 cin>>n>>m):
C++
struct fr{
    char gc(){
        static const int IN_LEN=1<<18|1;
        static char buf[IN_LEN],*s,*t;
        return (s==t)&&(t=(s=buf)+fread(buf,1,IN_LEN,stdin)),s==t?-1:*s++;
    }
    template <typename _Tp> inline fr & operator >> (_Tp&x){
        static char ch,sgn; ch = gc(), sgn = 0;
        for(;!isdigit(ch);ch=gc()){if(ch==-1)return *this;sgn|=ch=='-';}
        for(x=0;isdigit(ch);ch=gc())x=x*10+(ch^'0');
        sgn&&(x=-x); return *this;
    }
}io;
#define cin io

速度为关闭同步流后的 cin 的 44 倍(甚至更快)。

  1. 超级整形快写(照样用 cout<<114):
C++
struct fo{
    static const int OUT_LEN=1<<18;
    char obuf[OUT_LEN],*op;
    fo(){op=obuf;}
    ~fo(){fwrite(obuf,1,op-obuf,stdout);}
    inline void pc(char c){
        if(op==obuf+OUT_LEN)fwrite(obuf,1,OUT_LEN,stdout),op=obuf;
        *op++=c;
    }
    template <typename _Tp> inline fo&operator<<(_Tp x){
        static char stk[64],*top;top=stk;
        if(x<0)pc('-'),x=-x;
        do{*top++=x%10|'0';x/=10;}while(x);
        while(top!=stk)pc(*--top);return*this;
    }
    inline fo&operator<<(char c){pc(c);return*this;}
    inline fo&operator<<(const char*s){while(*s)pc(*s++);return*this;}
}out;
#define cout out

速度为关闭同步流的 cout 的 55 倍。

5. 卡常实战

这是我自创的卡常题,大家可以去试一下。

正常思路

复制代码直接提交。

33 pts33\ \text{pts}。

优化思路

看到示范代码,有很多不像人写的地方,直接去掉。

再次观察,发现就是在输入之后输出上一个输入的值。

不过不能开数组,因为 1.5×1071.5\times 10^7 会爆炸。

不妨定义变量 last,存储上一个输入的值。

输入之后,输出 last,last 再赋值为输入的数就行了。

记得把 last 初始化为 00。

关闭同步流。

C++
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll N=1e5+10;
int n;
ll x,last;
int main(){
    ios::sync_with_stdio(false),cin.tie(0);// cin/cout 加速
    cin>>n;
	while(n--){
		cin>>x;
		cout<<last<<'\n';
		last=x;
	}
    return 0;
}

还是没过。

但是,你忘记上文给出的快读快写了吗?

AC Code

C++
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll N=1e5+10;
int n;
ll x,last;
struct fr{
    char gc(){
        static const int IN_LEN=1<<18|1;
        static char buf[IN_LEN],*s,*t;
        return (s==t)&&(t=(s=buf)+fread(buf,1,IN_LEN,stdin)),s==t?-1:*s++;
    }
    template <typename _Tp> inline fr & operator >> (_Tp&x){
        static char ch,sgn; ch = gc(), sgn = 0;
        for(;!isdigit(ch);ch=gc()){if(ch==-1)return *this;sgn|=ch=='-';}
        for(x=0;isdigit(ch);ch=gc())x=x*10+(ch^'0');
        sgn&&(x=-x); return *this;
    }
}io;
#define cin io
struct fo{
    static const int OUT_LEN=1<<18;
    char obuf[OUT_LEN],*op;
    fo(){op=obuf;}
    ~fo(){fwrite(obuf,1,op-obuf,stdout);}
    inline void pc(char c){
        if(op==obuf+OUT_LEN)fwrite(obuf,1,OUT_LEN,stdout),op=obuf;
        *op++=c;
    }
    template <typename _Tp> inline fo&operator<<(_Tp x){
        static char stk[64],*top;top=stk;
        if(x<0)pc('-'),x=-x;
        do{*top++=x%10|'0';x/=10;}while(x);
        while(top!=stk)pc(*--top);return*this;
    }
    inline fo&operator<<(char c){pc(c);return*this;}
    inline fo&operator<<(const char*s){while(*s)pc(*s++);return*this;}
}out;
#define cout out
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
	while(n--){
		cin>>x;
		cout<<last<<'\n';
		last=x;
	}
    return 0;
}

记录显示,没有 IO 优化的代码跑第二个样例用了 790 ms790\ \text{ms},而正解代码只用了 35 ms35\ \text{ms}。

比对这三个代码相同但是语言不一样提交记录(1 2 3)。不难发现,运行时间最短的是 C++14,随后是 C++98 和 C++17。

所以,C++98 不一定最快。


这篇文章只是一个快要退役的蒟蒻写的,很多地方都有不足之处,欢迎各位大佬修正。

原文
存档评论1 条抓取于