0
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++のstd::pairの使い方

Last updated at Posted at 2025-01-26

目的

AtCoderでpairを使うので、使い方を自分用備忘録として残す。

使用ケース

pairをそのまま使用

基本的な使い方を示す。

using namespace std;

// 宣言と初期化
pair<string, int> employee("Kimura", 0000);
cout << employee.first << endl; // Kimura
cout << employee.second << endl; // 0000

// 各要素に値をセット
employee.first = "----";
employee.second = 1111;
cout << employee.first << endl; // ----
cout << employee.second << endl; // 1111

vectorと組み合わせて使用

using namespace std;

// pairの配列を宣言
vector<pair<string, int>> employees;

// 2人の社員を標準入力から追加
for (int i = 0; i < 2; ++i) {
    string name;
    int employeeNumber;
    cin >> name >> employeeNumber;
    employees.puhs_back(make_pair(name, employeeNumber));
}

// {"Yamada", 1234}と{"Tanaka", 5678}を追加したと仮定
cout << employees[0].first << " " << emploeyees[0].second << endl; // Yamada 1234
cout << employees[1].first << " " << emploeyees[1].second << endl; // Tanaka 5678
0
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
0
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?