0%

C++_tips

<bits/stdc++.h> in C++

引入一堆的头文件会显得冗杂,有时会出现CE。<bits/stdc++.h>包含了目前c++所包含的所有头文件,只要用了这个头文件就不用再写其他头文件。但这个头文件属于gcc 的内部实现,不是标准库头文件,可能导致不可移植的问题。

Disadvantages of bits/stdc++

  • bits/stdc++.h is not a standard header file of GNU C++ library. So, if you try to compile your code with some compiler other than GCC it might fail; e.g. MSVC do not have this header.
  • Using it would include a lot of unnecessary stuff and increases compilation time.
  • This header file is not part of the C++ standard and is therefore, non-portable, and should be avoided.
  • Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Advantages of bits/stdc++

  • In contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time sensitive.
  • This also reduces all the chores of writing all the necessary header files.
  • You don’t have to remember all the STL of GNU C++ for every function you use.

So, the user can either use it and save the time of writing every include or save the compilation time by not using it and writing necessary header files.

OJ中的常用术语

简写 全拼 中文
OJ Online Judge 在线判题系统
AC Accepted 通过
WA Wrong Answer 答案错误
TLE Time Limit Exceed 超时
OLE Output Limit Exceed 超出输出限制
MLE Memory Limit Exceed 超内存
RE Runtime Error 运行时错误
PE Presentation Error 格式错误
CE Compile Error 无法编译

std::ios::sync_with_stdio(false)

(如果用了using namespace std;就可以去掉前面的std::)

这句话在IO之前将stdio解除绑定,这样做了之后要注意不要同时混用cin/cout和scanf,sscanf, getchar, fgets/printf之类。

在默认的情况下cin绑定的是cout,每次执行 << 操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。

1
2
3
4
5
6
7
8
#include<iostream>
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
//IO
}

取消同步的目的,是为了让cin不超时,另外cout的时候尽量少用endl,换用”\n”,也是防止超时的方法。若用scanf,printf就不用考虑这种因为缓冲的超时了。


每一次都不得不感慨——他的代码像是一件艺术品!