方法1
ios::sync_with_stdio(false);
方法2
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
方法3
尽量用"\n"替换可以替换的 endl 。(考虑流输出)
方法1 和方法2 解释
sync_with_stdio()
这个函数是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑在了一起。
std::ios::sync_with_stdio(false);
iostream默认是与stdio关联在一起的,以使两者同步,因此消耗了
iostream不少性能。
C++中的std :: cin和std :: cout为了兼容C,保证在代码中同时出现std :: cin
和scanf或std :: cout和printf时输出不发生混乱,
所以C++用一个流缓冲区来同步C的标准流。
通过std :: ios_base :: sync_with_stdio函数设置为false后
可以解除这种同步,让std :: cin和std :: cout不再经过缓冲区,
iostream的性能就会提高了很多倍。
因此,当解除同步之后,
注意不要与scanf和printf混用以免出现问题。
tie()
tie()用来绑定stream,空参数则返回当前的输出流指针。
tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。
std :: cin默认是与std :: cout绑定的,
所以每次操作的时候都要调用fflush,这样增加了IO的负担,
通过tie(nullptr)来解除std :: cin和std :: cout之间的绑定,进一步加快执行效率。
【小重点】 空指针概念
不指向任何对象的指针
nullptr 是 C++11中的关键字,表示空指针
NULL 是一个宏定义,在c和c++中的定义不同,
C 中 NULL 为 (void * ) 0 ,
而 C++ 中 NULL 为整数 0 。
在C++中(void *)不能转化为任意类型的指针,即 int *p = ( void * )是错误的,
但int * p = nullptr是正确的。
nullptr是一个特殊类型字面值,类型为std::nullptr_t,
可以转换为任意其他的指针类型。
生成空指针的方法:
int * p1 = nullptr; // 等价于 int * p1 = 0;
int * p2 = 0; // 直接将 p2 初始化为字面常量 0
// 需要首先 #include cstdlib
int * p3 = NULL; // 等价于 in * p3 = 0;
方法3 解释
cout << ... << endl;
在终端显示. . .的内容后换行,同时刷新缓冲区的内容。
相当于 cout << . . . << “\n”<< flush; 。
cout << ... << "\n";
仅在终端显示. . . 的内容后换行。
使用场景
在考虑效率且没有必要刷新输出流时使用cout << . . . << "\n";
在一些大程序需要刷新输出流时使用cout << . . . << endl;
总结
特别是方法 1 和 方法 2,
ios::sync_with_stdio(false);
// 让std :: cin和std :: cout不再经过缓冲区
这个可以进一步优化为
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// 通过tie(nullptr)来解除std :: cin和std :: cout之间的绑定,进一步加快执行效率。