3
5

More than 5 years have passed since last update.

競プロメモ(C++)

Last updated at Posted at 2019-02-04

一般常識


C++に関する常識たち
略号 説明
Int ("%d") 32 Bit integer
Long ("%ld") 64 bit integer
Char ("%c") Character type
Float ("%f") 32 bit real value
Double ("%lf") 64 bit real value

変数は必ず初期化しないと意味分からない値が入ってる

Include


Include all library
  • 全部込み込みでインクルード
  • 環境によってはコンパイルに時間がかかるので要注意

#include <bits/stdc++.h>

Define

  • よく使うやつ

ループ文のマクロ化

#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
  • TODO
    • Range-based Forについて調べる → Qiita

型定義

#define INF 2e9
#define ll long long
#define ALL(v) v.begin(), v.end()

入出力

  • cin, coutは遅い
  • cin, coutを使うなら以下を設定する
    • cinが実行時にcoutをフラッシュするのを阻止
    • stdioとの同期解除

cin.tie(0);
ios::sync_with_stdio(false);

Int, Double, etc.

for (int i = 0; i < 3; ++i) {
    scanf("%d", &a[i]);
}

endl
  • endlは実行時にバッファを吐き出すのでボトルネック

cout << x * x * x << "\n";

一行入力

# 2 8 7 1 4 2 3 5
REP(i, loop){
    cin >> input;
}

その他


型変換
  • String → Int

stoi();
  • Int → String

to_string();

  • Char → Int

# charのnumberが48番目から始まるのでその分調整
(int)ch - 48;

値の交換

#include <algorithm>
swap(a, b);

降順sort
  • 昇順sortは第3引数不要

#include <algorithm>
#include <functional>   // greater<int> はfunctionalヘッダ

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
sort(arr, arr+9, greater<int>());

String入力からIntのVector生成

vector<int> parseInts(string str) {
    stringstream x(str);
    vector<int> vc;

    while(!x.eof()){
        int i = 0;
        x >> i;
        x.ignore();
        vc.push_back(i);
    }
    return vc;
}

Listの長さ

sizeof(list) / sizeof(list[0])

1次元配列の初期化

# 宣言
void initialize_1d_list(int* list, int n){
    REP(i, n){
        list[i] = 0;
    }
}

# 呼び出し
initialize_1d_list(list, sizeof(list) / sizeof(list[0]));

1次元配列の表示

void display_1d_list(int* list, int n){
    REP(i, n){
        cout << list[i] << "\t";
    }
    cout << "\n";
}

2次元配列の初期化

void initialize_2d_list(int* list, int n, int m){
    REP(i, n){
        initialize_1d_list(&list[i * m], m);
    }
}

2次元配列の表示

void display_2d_list(int* list, int n, int m){
    REP(i, n){
        display_1d_list(&list[i * m], m);
    }
}
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5