emplace_back を使ってみる (C++)
C++
Published: 2020-03-29

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, string> P;
typedef tuple<ll, ll, string> T;

int main() {

    vector<P> v;
    v.push_back(P(1, "aaa"));
    v.emplace_back(2, "bbb");
    cout << "pair" << endl;
    for (int i = 0; i < v.size(); i++) {
        cout << v[i].first << " " << v[i].second << endl;
    }

    vector<T> v2;
    v2.push_back(T(1, 100, "mmm"));
    v2.emplace_back(2, 200, "nnn");

    cout << "tupple" << endl;
    for (int i = 0; i < v2.size(); i++) {
        cout << get<0>(v2[i]) << " " << get<1>(v2[i]) << " " << get<2>(v2[i]) << endl;
    }
}

出力結果

pair
1 aaa
2 bbb
tupple
1 100 mmm
2 200 nnn

参考