LoginSignup
2
1

More than 3 years have passed since last update.

C++ STL tupleのコード集

Last updated at Posted at 2020-06-10

概要

STL(Standard Template Library)のtuple関係のコード集です。対応確認環境はMicrosoft Visual Studio 2019 Communityのstd:c++latest (C++20 draft)です。最新のC++では制約が異なる可能性があります。

共通事項

  • using namespace std;によりstd::は省略しています。

出力用の関数

出力用に次の関数を定義しています。共通部分なので以降のコードでは省略します。

vectorを一行に出力

template <typename T>
void output_singleline(const vector<T>& v)
{
    constexpr wchar_t sep[] = L", ";
    wstringstream wss;
    for (const auto& i : v)
    {
        wss << i << data(sep);
    }
    if (const auto& s = wss.str(); !empty(s))
    {
        wcout << s.substr(0, s.length() - size(sep) + 1);
    }
    wcout << endl;
}

範囲forでmapのキーに指定したtupleを構造化束縛する

構造化束縛はネストの分解に対応していないので範囲forの初期化式では直接タプルを構造化束縛することはできません。しかし、forブロック内で改めて構造化束縛することでキーに指定したtupleを分かりやすく参照できます。

#include <iostream>
#include <string>
#include <tuple>
#include <map>

using namespace std;

int main()
{
    map<tuple<int, wstring>, int> m1{
        {{0, L"a"}, 100},
        {{1, L"b"}, 101},
        {{2, L"c"}, 102},
        {{3, L"d"}, 103},
        {{4, L"e"}, 104}};

    for (const auto& [key, value] : m1)
    {
        const auto& [i, s] = key;
        wcout << L"{{" << i << L", " << s << L"}, " << value << L"}" << endl;
    }

    return 0;
}
出力
{{0, a}, 100}
{{1, b}, 101}
{{2, c}, 102}
{{3, d}, 103}
{{4, e}, 104}

mapのキーに指定したtupleの要素からベクトルを作成する

get<i>(tuple)tuplei番目の要素を取得できます。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
#include <map>
#include <vector>

using namespace std;

template <typename T>
void output_singleline(const vector<T>& v);

int main()
{
    map<tuple<int, wstring>, int> m1{
        {{0, L"a"}, 100},
        {{1, L"b"}, 101},
        {{2, L"c"}, 102},
        {{3, L"d"}, 103},
        {{4, L"e"}, 104}};

    vector<wstring> second_keys;
    second_keys.reserve(size(m1)); // optional
    transform(cbegin(m1), cend(m1), back_insert_iterator(second_keys),
        [](const auto& kv) {
            const auto& [key, value] = kv;
            return get<1>(key);
        });

    output_singleline(second_keys);

    return 0;
}
出力
a, b, c, d, e
2
1
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
2
1