2014-12-01から1ヶ月間の記事一覧

いもす法

http://imoz.jp/algorithms/imos_method.html

GCD 最大公約数を求める

c++

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

検索したハイライトを解除

vim

:nohで解除される便利だ。検索のハイライトが邪魔くさい - 百舌日記

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

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>…

バイナリファイルを作成する

//wb: 書き込みモードで新規に作成 file = open("hoge.txt", "wb:UTF-8") file = File.open("hoge.txt", "wb:UTF-8") //w+b: 書き込み読み込み両用モードで新規に作成 file = open("hoge.txt", "w+b:UTF-8") file = File.open("hoge.txt", "w+b:UTF-8")

ファイルを作成する

//w: 書き込みモードで新規に作成 file = open("hoge.txt", "w:UTF-8") file = File.open("hoge.txt", "w:UTF-8") //w+: 書き込み読み込み両用モードで新規に作成 file = open("hoge.txt", "w+:UTF-8") file = File.open("hoge.txt", "w+:UTF-8")

ファイルを開く

// 同じ意味 rは読み込みモード(省略時もこれ) file = open("hoge.txt", "r:UTF-8") file = File.open("hoge.txt", "r:UTF-8") // 読み書き両用モード file = open("hoge.txt", "r+:UTF-8") // 追加書き込みモード file = open("hoge.txt", "a:UTF-8") // …

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; } } } }