加快输入数据读入速度的函数

张文泰 posted @ 2010年4月20日 01:48 in Code and Develop with tags 代码 , 3532 阅读

最近做SPOJ,发现很多题目的读入都是有大幅度优化余地的。事实上,在C++中,使用scanf()读入整数或者实数的速度都非常慢。我们可以通过一次读入一整行的来加快速度,方法是使用gets()。

对于gets()这个函数,GCC的文档建议不要使用。我个人的感觉是只要使用得当,这个函数还是大有用处的。比如下面的代码:

char buf[10000],*o;
inline int getint() {
  while (!isdigit(*o) && *o!='-') ++o;
  int r = 0,f = *o=='-'?++o,1:0;
  while (isdigit(*o)) r = r*10+*o++-'0';
  return (f?-r:r);
}

这个代码提供了一个getint()的函数来加快读入整数的速度。我们使用o = gets(buf),时候就可以进行相关的操作了。在这个函数的基础上稍作改进还可以读入实数等等。


本作品遵循“署名-非商业性使用-相同方式共享 3.0 Unported”协议,转载请注明来自richard-desktop
Creative Commons License
NCERT Evs Question P 说:
2022年9月21日 20:25

We learned a lot from the Environmental Studies or Environmental Education (EVS) class, and it also taught us how to behave well in social situations. NCERT EVS Question Paper for 7th Grade, 2023, with all subjects answered. NCERT Evs Question Paper Class 7 The NCERT STD-7 EVS Question Bank 2023 has been created based on the changed syllabus and curriculum by subject specialists. The adjustments may enhance the student's abilities to earn top marks.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter