关于读入输出

cin, cout

cin 与 cout 由于语法简单,自动识别类型,深受许多初学者的青睐。不过又因为cin cout 个人认为速度较慢,所以初学阶段过后用的也就不多了。而今天这一节课,真的是怀疑世界啊!!! (原来我一前的认知存在不少问题)

然后介绍一下:  ios::sync_with_stdio(false);

ios::sync_with_stdio(false);
//用以优化cin, cout, 使其速度接近scanf, printf.
//但是一旦开启此优化,不可再使用scanf, printf.否则可能Re。
int a;
cin >> a;
a = 1;
cout << a << endl;


scanf, printf

这种方法是很多人放弃cin后的第一个选择:
scanf的使用:

int x;
scanf("%d", &x);
double y;
scanf("%lf", &y);
char s[100];
scanf("%s", s);
scanf("%s", s + 1); //下标从1开始

long long z;
scanf("%lld", &z); //unix(Linux Ubunut Mac OSX)
scanf("%I64d", &z); //WIN32
//WIN64以上方法都可以

那么考试时怎么办呢??
CCF提供XP系统(233确是事实),评测却要用Linux,考场上可能会产生一些问题:你调试程序要写I64d,写完最后改成lld也不知有没有疏漏。
于是可以程序里加入

#ifdef WIN32
#define LL "%I64d"
#else
#define LL "%lld"
#endif

然后就可以各个系统通用了。

printf的使用
类似scanf,但是无地址符

nt x;
printf("%d", x);
double y;
printf("%lf", y);
char s[100];
printf("%s", s);
printf("%s", s + 1); //下标从1开始

long long z;
printf("%lld", z); //unix(Linux Ubunut Mac OSX)
printf("%I64d", z); //WIN32



速度比较

比如输出1e7个数,我们来比较一下各种方法的用时

cout 20.91s
printf 30.35s
print() 1.47s //输出优化

而输入1e7个数呢
scanf 9.78s
cin 12.23s
cin(优化后)2.18s
read() 2.98s

于是发现无优化的cout已经可以干掉printf,而优化后的cin更是直接完爆scanf!!!
(并不符合我从前的认知,却是ZHX长者亲测的事实,教师机挺慢的。。。)

但还是坚持推广一下读入优化。。。

int read()
{
int x = 0;
int k = 1;
char c = getchar();

while (!isdigit(c))
if (c == '-') k = -1, c = getchar();
else c = getchar();
while (isdigit(c)) 
x = x * 10 + c -'0',
c = getchar();

return x * k;
} //被cin干掉,无脸见人。。。


那么更为重要的是输出优化
//主要是将数据转为字符输出

int a;
int l = 0;
char s[80000000]
void print(int v)
{
int x = 0, y = 0;
while (v)
{
++x; 
y = y * 10 + v % 10;
v /= 10;
}
for (int i = 1; i <= n; ++i)
{
++l;
s[l] = y % 10 + '0';
y /= 10;
}
++l;
s[l] = '
';
}
原文地址:https://www.cnblogs.com/yanyiming10243247/p/9485907.html