Skip to content

Instantly share code, notes, and snippets.

@goropikari
Last active February 26, 2018 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goropikari/481c843eb4b8c00264a17fdefb55e4d7 to your computer and use it in GitHub Desktop.
Save goropikari/481c843eb4b8c00264a17fdefb55e4d7 to your computer and use it in GitHub Desktop.
C++メモ

標準入力・出力

#include <iotream>
using namespace::std;
  
int main() {
    int a, b;
    cin >> a >> b;
    cout << a + b << std::endl;
    return 0;
}

標準入力

スペース区切り or 改行区切りで2文字入力した場合

int a, b;
cin >> a >> b;

スペース区切りの文字列を一列ごと入れる場合

string s;
getline(cin, s);

標準出力

型を気にする必要はない

cout << "hoge" << 2 << "piyo" << endl;

ファイルの読み込み、書き込み

input.txtから2つの数を読み込み、その数の和をoutput.txtに保存する場合

#include <fstream>
std::ifstream cin("input.txt");
std::ofstream cout("output.txt");
  
int main() {
    int a, b;
    cin >> a >> b;
    cout << a + b << std::endl;
    return 0;
}

ソート, sort

https://codezine.jp/article/detail/6020

// 配列, array, vector を昇順にソートする
int a[N];
array<int,N> ar;
vector<int> v;

sort(a, a+N); // 配列
sort(ar.begin(), ar.end()); // array
sort(v.begin(), v.end()); // vector

連想配列、辞書、ハッシュ

#include <iostream>
#include <unordered_map>
using namespace::std;


int main(int argc, char const* argv[])
{
    unordered_map<string, int> dict;
    string str[] = {"Tokyo", "Kanda"};
    int num[] = {100, 200};
    for (int i = 0; i < 2; i++) {
        dict[str[i]] = num[i];
    }

    for (int i = 0; i < 2; i++) {
        cout << dict[str[i]] << endl;
    }

    return 0;
}

result

100
200

template

template <class T>
T foomax(T x, T y){
  if (x > y){
    return x;
  }else{
    return y;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment