Some C++ Tricks from Codeforces

Some C++ Tricks from Codeforces

Here, In folder C++.

I choose some of them which is useful for me and note them in these blog.

all(x)

1
#define all(x) x.begin(), x.end

before:

1
2
3
vector<int> a;
// some operation...
sort(a.begin(), a.end());

now:

1
2
3
vector<int> a;
// some operation...
sort(all(a));

before:

1
2
3
vector<int> a;
// some operation...
sort(a.begin() + 1, a.end())

now:

1
2
3
vector<int> a;
// some operation...
sort(1 + all(x));

std::unique

We know that std::unique won’t delete the rest number, but put them in the end.For example, vec = {1, 1, 2, 2, 3, 2, 1} may become {1, 2, 3, 2, 1, 2, 1}. It not good.We can do like this:

1
2
sort(all(vec));
vec.resize(unique(all(vec)) - vec.begin());

read()

1
2
3
4
5
6
inline int read() {
int x = 0, f = 0; char c = 0;
while (!isdigit(c)) f |= c == '-', c = getchar();
while (isdigit(c)) x = (x << 3) + (x << 1) + (c & 15), c = getchar();
return f ? -x : x;
}

Faster and Shorter.

before:

1
2
int n;
cin >> n; // or scanf("%d", &n);

now:

1
int n = read();

我为什么要用阴文。。。写不下去了。。。


std::generate

将给定的区间用给定的函数赋值。举个例子:

1
2
3
4
5
6
7
8

int x = 0;
int up() { return ++ x; }

vector<int> a(4);
generate(all(a), up);
// a = {1, 2, 3, 4}

配合 read 可以快速读入数组。

1
for (int i = 1; i <= n; i ++) cin >> a[i];

现在变成了

1
generate(a + 1, a + n + 1, read);

使用 generate_n 还可以写成:

1
generate_n(a + 1, n, read);

输出一个数的二进制

使用 std::bitset 可以这样:

1
2
3
int n;
// ...
cout << bitset<31>(n) << endl;

lambda 表达式

见我的另一篇 blog。

std::max

1
int r = max({a, b, c});

{}

1
2
pair<int, int> x = {1, 2} // 等价于 make_pair(1, 2)
vector<int> y = {1, 1, 4, 5, 1, 4} // 对 vector 直接赋值
  • 好像没了

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!