Namespaces
Variants

std::set<Key,Compare,Allocator>:: emplace

From cppreference.net

template < class ... Args >
std:: pair < iterator, bool > emplace ( Args && ... args ) ;
(C++11以降)
(constexprはC++26以降)

キーがコンテナ内に存在しない場合、与えられた args を使用してその場で構築された新しい要素をコンテナに挿入します。

新しい要素のコンストラクタは、 emplace に渡された引数と全く同じ引数で呼び出され、 std:: forward < Args > ( args ) ... によって転送されます。 要素は、コンテナ内に同じキーを持つ要素が既に存在する場合でも構築される可能性があり、その場合、新しく構築された要素は直ちに破棄されます。

value_type EmplaceConstructible でなく、 set 内で args から構築できない場合、動作は未定義です。

イテレータや参照は無効化されません。

目次

パラメータ

args - 要素のコンストラクタに転送する引数

戻り値

挿入された要素(または挿入を妨げた要素)へのイテレータと、挿入が行われた場合にのみ bool 値が true に設定されるペア。

例外

何らかの理由で例外がスローされた場合、この関数は何も効果を持ちません( strong exception safety guarantee )。

計算量

コンテナのサイズに対して対数的。

注記

emplace の注意深い使用により、新しい要素を不必要なコピー操作やムーブ操作を回避しながら構築することが可能になります。

#include <chrono>
#include <cstddef>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <set>
class Dew
{
private:
    int a, b, c;
public:
    Dew(int _a, int _b, int _c)
        : a(_a), b(_b), c(_c)
    {}
    bool operator<(const Dew& other) const
    {
        return (a < other.a) ||
               (a == other.a && b < other.b) ||
               (a == other.a && b == other.b && c < other.c);
    }
};
constexpr int nof_operations{101};
std::size_t set_emplace()
{
    std::set<Dew> set;
    for (int i = 0; i < nof_operations; ++i)
        for (int j = 0; j < nof_operations; ++j)
            for (int k = 0; k < nof_operations; ++k)
                set.emplace(i, j, k);
    return set.size();
}
std::size_t set_insert()
{
    std::set<Dew> set;
    for (int i = 0; i < nof_operations; ++i)
        for (int j = 0; j < nof_operations; ++j)
            for (int k = 0; k < nof_operations; ++k)
                set.insert(Dew(i, j, k));
    return set.size();
}
void time_it(std::function<int()> set_test, std::string what = "")
{
    const auto start = std::chrono::system_clock::now();
    const auto the_size = set_test();
    const auto stop = std::chrono::system_clock::now();
    const std::chrono::duration<double, std::milli> time = stop - start;
    if (!what.empty() && the_size)
        std::cout << std::fixed << std::setprecision(2)
                  << time << " for " << what << '\n';
}
int main()
{
    time_it(set_insert, "cache warming...");
    time_it(set_insert, "insert");
    time_it(set_insert, "insert");
    time_it(set_emplace, "emplace");
    time_it(set_emplace, "emplace");
}

出力例:

630.58ms for cache warming...
577.16ms for insert
560.84ms for insert
547.10ms for emplace
549.44ms for emplace

関連項目

ヒントを使用して要素をその場で構築する
(公開メンバ関数)
要素を挿入する またはノード (C++17以降)
(公開メンバ関数)