【C++】A trick I learned:put boilerplate code into constructor of a struct

I learned this trick from hitonanode's submission on AtCoder.

The trick is like

struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_;

What I used to do is like

#define FAST_READ ios::sync_with_stdio(false); cin.tie(nullptr);
int main() {
    FAST_READ
    cout << fixed << setprecision(10);
    // ...
}

using this trick, the code becomes

struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(10); }; } fast_ios_;
int main() {
    // ...
}

I think macros are better avoided when alternatives are available.

猜你喜欢

转载自www.cnblogs.com/Patt/p/11796583.html