• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

cppのスニペット

date: 2020-11-04 excerpt: cppのスニペット

tag: cppスニペット


cppのスニペット

概要

  • 便利に使えるスニペット集

まとめて最初に記すと便利

#include <iostream>
#include <algorithm>
#include <vector>
#include <bits/stdc++.h>
#include <map>
#include <cmath>
#include <cassert>
#include <string>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define print(s) std::cout << s << std::endl;
using namespace std;
using ll=long long;
const long long INF = 1LL << 60;
template<class T> void chmin(T& a, T b) { if(a > b) { a = b; } }
template<class T> void Sort(vector<T>& input) { std::sort(input.begin(), input.end()); }
template<class T> std::vector<T> mk_vec(int size,T init) { return std::vector<T>(size, init); }
template<class T> std::vector<std::vector<T>> mk_mat(int H, int W, T init) { return std::vector<std::vector<T>>(H, std::vector<T>(W, init)); }
template<class T> void print_it(T t){for (const auto& ele: t) std::cout << ele << "; "; std::cout << std::endl; }
template<class T> vector<T> accumulate_vec(vector<T> v) { // accumulate関数
    int size = v.size(); vector<T> ret; T buf{}; for(auto tmp: v) { buf += tmp; ret.push_back(buf); }; return ret;
}
template<class T> T sum_vec(vector<T> vec) { // sum関数
    T buf{}; for(auto tmp: vec) buf += tmp; return buf;
}

math

  • cbrtはx^(1/3)を求める関数
  • sqrtはx^(1/2)

min, max

#include <algorithm>
...
int tmp_res[n];
cout << *min_element(tmp_res, tmp_res+n) << endl;

bit operation

e.g.

1 << 0
>> "00000000"

1 << 1
>> "00000001"

1 << 3
>> "00000011"

ref. atcoder abc045_c

そのビットの状態で状態を変えるには、以下のようなコードがテンプレートになる

for(int bit=0; bit < (1 << n.size()-1); bit++) {
	cout << bitset<32>(bit) << endl;

	for(int i=0; i< n.size(); ++i) {
		if(bit & (1 << i)) { // ここでbitのn-bit目が1で(1 << i)とand条件を取ることでわかる
		}
	}
}

note. bit操作はint型しか受け付けない

vector

dpなどを使う際に十分な速度がvectorででる

e.g. 長さMでvector<bool>でfalseで初期化する

vector<bool> dp(M, false);

vectorの最小値

変数vがあるとき

*min_element(v.begin(), v.end())

が最小値

binary_search, upper_bound, lower_bound

二分探索であるの上界、下界のpointerを高速に返す

upper_bound(ある値の上界のvのindex)

v.end() - upper_bound(v.begin(),v.end(),b);

lower_bound(ある値の下界のvのindex)

lower_bound(v.begin(),v.end(),b) - v.begin();


cppスニペット Share Tweet