1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++競技プロ用メモ

1
Last updated at Posted at 2025-05-17

基本形

#include <iostream>
// 必要に応じてライブラリを追加
using namespace std;
// ここにマクロ関連を書く
int main()
{
    // ここにコードを書く
    cout << "Hello C++!" << '\n';
    return 0;
}

標準入出力

  • データの流れを抽象化した仕組みをストリームと呼ぶ
  • 標準入出力ストリーム
    • cin: 標準入力
    • cout: 標準出力
    • cerr: エラー出力
    • clog: バッファありエラー出力
    • これらは iostream に定義されている

入力

  • >>演算子で入力ストリームから抽出する

一つ受け取る

int N;
cin >> N;

二つ受け取る

int N, M;
cin >> N >> M;
  • 半角スペース区切りでも,改行でも同じ扱い
N M

でも

N
M

でも,どちらも cin >> N >> M で受け取り可能

  • 型が違くても受け取れる
int N;
string S;
cin >> N >> S;
  • 行全体が欲しい
    cinは,次の(半角スペースまたは改行)まで読み込む
    例えば半角スペースを含む文字列を受け取りたい場合getlineを使う
string S;
getline(cin, S);
cin.ignore(); // getlineは改行の処理はしてくれないので明示的に行う

配列やベクトルの場合はループを使う

int A[10];
for(int i = 0; i < 10; i++) cin >> A[i];

標準出力

  • <<出力ストリームに挿入
  • endlは改行

一つを出力

cout << "Hello!" << endl;
// ==> Hello!

複数を出力

cout << "Hello" << ' ' << "C++!" << endl;
// ==> Hello C++!

形状を整える

  • xx桁まで出力など
#include <iomanip>
double pi = 3.14159265;
cout << pi << endl;
// ==> 3.14159
cout << fixed << setprecision(10) << pi << endl; // 小数点10桁まで
// ==> 3.1415926500

IO高速化

保守性度外視の裏技
GCCの cin は以下を使うことで十分高速にできる

ios::sync_with_stdio(false); // CとC++のストリームを分離
cin.tie(nullptr);            // 入出力の結合を外し不要なフラッシュを防ぐ

endl'\n'

どちらも改行を表すがendlはバッファをフラッシュするので遅くなる.特に繰り返し出力が必要な場合(クエリ処理など)ではなるべく'\n'を使いたい

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?