std:pairを使う

もくじ
https://tera1707.com/entry/2022/02/06/144447

やりたいこと

C++のコードを見る中で、std::pair<int, std::string> みたいなのが出てきた。

どういう使い方するのか知りたい。

サンプルコード

こういうコードを書いて実験した。

#include <iostream>
#include <utility>
#include <string>

std::pair<int, std::string> MyFunc()
{
    auto a = std::make_pair(1, "aaa");
    return a;
}

int main()
{
    std::cout << "Hello World!\n";

    // std::pairの基本的な使い方サンプル
    std::pair<int, std::string> p1(1, "apple");
    std::cout << "p1.first: " << p1.first << ", p1.second: " << p1.second << std::endl;

    // std::make_pairを使った生成
    auto p2 = std::make_pair(2, "banana");
    std::cout << "p2.first: " << p2.first << ", p2.second: " << p2.second << std::endl;

    // std::pairの配列
    std::pair<int, std::string> fruits[] = {
        {3, "orange"},
        {4, "grape"},
        {5, "melon"}
    };
    for (const auto& fruit : fruits) {
        std::cout << "fruits: " << fruit.first << ", " << fruit.second << std::endl;
    }

    // 関数内でstd::pairを作ってreturnさせて、それをうけとることも出来る
    auto ret = MyFunc();
    std::cout << "ret.first: " << ret.first << ", ret.second: " << ret.second << std::endl;

    // ばらしてうけることも出来る(C++17)
    auto [a, b] = MyFunc();

    std::cout << "a: " << a << ", b: " << b << std::endl;

    return 0;
}

調べたこと

下記サイトによると、「std::make_pair」はほとんどの場合に不要、らしい。

https://cpprefjp.github.io/reference/utility/pair.html

また、上のコードのMyFuncは、下記のようにも書ける。(なので、std::make_pairがいらないということか)

std::pair<int, std::string> MyFunc()
{
    return { 1, "aaa" };
}

あと、C++17以上だが、pairを返す関数を、ばらして受けることもできる。

    // ばらしてうけることも出来る(C++17)
    auto [a, b] = MyFunc();

備考

std::pairは、2つまでの値を扱うが、3つ以上を扱えるstd::tubleがあるらしい。C#のタプルと同じようなものか。

後日また見てみる。

参考

cpprefjp - C++日本語リファレンス

https://cpprefjp.github.io/reference/utility/pair.html