c++

10進数から2進数に変換 (std::bitset)

c++

int n = 100 // 8ビット長のビット集合を生成 bitset<8> b(n); // 01100100 cout << b << endl; C++ ビット集合(std::bitset)あるものは使おう。

GCD 最大公約数を求める

c++

int gcd(int a, int b) {return a == 0 ? b : gcd(b%a,a);} ちなみにGreatest Common Divisorの略。

コンストラクタの初期化構文

c++

struct S{ int a, b, c; S(int a, int b, int c):a(a),b(b),c(c){} }; vector<S> v; v.push_back(S(1,2,3)); これをデフォルトコンストラクタと書いてあるページもあったけど、ポケットリファレンスにはデフォルトコンストラクタは仮引数をひとつも持たないと書</s>…

string int

c++

intとstringの変換。 C++11だけしか動かない #include <iostream> #include <string> int n = 100; string str_n; str_n = to_string(n); // "100" n = n + stoi(str_n); // 200</string></iostream>

std::distance

c++

イテレータはわかるんだけど添字がほしいなってとき。 #include <iostream> #include <vector> #include <algorithm> vector<int> v; vector<int>::iterator it; // VALUEと同じかそれ以上の値のイテレータを求める it = lower_bound(v.begin(),v.end(), VALUE); // その値の添字を求める int pos = </int></int></algorithm></vector></iostream>…

std::lower_bound

c++

同じかそれ以上の値が出現する場所のイテレータを返す。 #include <iostream> #include <vector> #include <algorithm> vector<int> v; vector<int>::iterator pos; for(int i = 0; i < 100; i++){ v.push_back(i); } pos = lower_bound(v.begin(), v.end(), 10); int num = *pos; cout << num << en</int></int></algorithm></vector></iostream>…

(構造体の中で関数) & (タプルを使って比較演算定義)

c++

struct S{ int w,h,l; S(int w, int h):w(w), h(h){ l = w*w + h*h; } }; bool operator<(const S& a, const S& b) { // l、hの順番で優先順位を付けて比較 return tie(a.l, a.h) < tie(b.l, b.h); } 関数の定義の書き方がいまいちよくわからない。こういう…

VimのsyntasticをC++11で使う

vim QuickRunとsyntasticで clang++のC++11を使う方法ここを見よう

演算子のオーバーロード

c++

//pの小さい順にソートして同じだった時はdが小さい順にソートする struct Prince{ int d; int p; bool operator<(const Prince& right) const { return p == right.p ? d < right.d: p < right.p; } }; ソートが出来るようになって便利。もしソートする要素…

fill, fill_n コンテナを指定した値で埋める

c++

#include <algorithm> #include <vector> vector<int> v = {1,2,3,4,5}; // 0で埋める fill(v.begin(),v.end(),0); //先頭から2つを0で埋める fill_n(v.begin,2,0) int a[100]; //0で初期化 fill( int *)a, (int *)a+100, 0) int b[10][100]; //2次元配列を0で初期化 fill( (int *)b,</int></vector></algorithm>…

素数生成

c++

#define N 1000001 int prime[N]; void make_prime(){ //primeが0だったら素数 fill(prime,prime+N,0); prime[0] = prime[1] = 1; for(int i = 2; i*i < N; i++){ if(prime[i] == 0){ for(int j = 2*i; j < N; j+=i){ prime[j] = 1; } } } }