MiyanoShiho's blog

By MiyanoShiho, history, 4 years ago, In English

Recently I wrote a fast read template and wanted to adapt it to multiple parameters.

The following is how I implemented it:

template <class T>
inline void read(T &x) {
  x = 0; int ch = getchar(); bool f = false;
  while (ch < '0' || ch > '9')
    ch = getchar(), f = (ch == '-') ? 1 : 0;
  while (ch >='0' && ch <='9')
    x = (x << 1) + (x << 3) + (ch ^ 48),
      ch = getchar();
  if (f) x = -x;
}

template <class T, class ...Args>
void read(T& x, Args... rest) {
  read(x), read(rest...);
}

However it completely crashed!

When I input 1 2 3 4, it just came out with 4 random int.

How should I improve that?

THX. XD

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it
template <class T, class ...Args>
void read(T& x, Args... rest) {
  read(x), read(rest...);
}

If you look at this function, and second template parameter it doesn't have the ampersand sign. So if you add it so that it becomes

template <class T, class ...Args>
void read(T& x, Args&... rest) {
  read(x), read(rest...);
}

And this works for me on my local machine.