名前空間
変種
操作

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

提供: cppreference.com
< cpp‎ | container‎ | set
 
 
 
 
template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
(C++11以上)

コンテナにそのキーを持つ要素がなければ、指定された args を使用してその場で構築される新しい要素をコンテナに挿入します。

emplace を注意深く使用すれば、不必要なコピーやムーブを避けながら新しい要素を構築することができます。 新しい要素のコンストラクタは、 emplace に与えられたものとまったく同じ引数が std::forward<Args>(args)... によって転送されて、呼ばれます。 コンテナにそのキーの要素がすでに存在している場合でも、要素は構築されるかもしれません。 その場合、新しく構築された要素は即座に破壊されます。

どのイテレータも参照も無効化されません。

目次

[編集] 引数

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

[編集] 戻り値

挿入された要素、または挿入しなかった場合は既存の要素を指すイテレータと、挿入が発生したかどうかを表す bool (挿入が発生した場合は true、しなかった場合は false) から構成される、ペアを返します 。

[編集] 例外

何らかの操作によって例外が投げられた場合、この関数は何の効果も持ちません。

[編集] 計算量

コンテナのサイズの対数。

[編集]

#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
 
class Dew
{
  private:
    int a;
    int b;
    int c;
 
  public:
    Dew(int _a, int _b, int _c)
      : a(_a), b(_b), c(_c)
    {}
 
    bool operator<(const Dew &other) const
    {
      if (a < other.a)
        return true;
      if (a == other.a && b < other.b)
        return true;
      return (a == other.a && b == other.b && c < other.c);
    }
};
 
const int nof_operations = 120;
 
int 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();
}
 
int 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 timeit(std::function<int()> set_test, std::string what = "") {
  auto start = std::chrono::system_clock::now();
  int setsize = set_test();
  auto stop = std::chrono::system_clock::now();
  std::chrono::duration<double, std::milli> time = stop - start;
  if (what.size() > 0 && setsize > 0) {
    std::cout << std::fixed << std::setprecision(2)
        << time.count() << "  ms for " << what << '\n';
  }
}
 
int main()
{
  set_insert();
  timeit(set_insert, "insert");
  timeit(set_emplace, "emplace");
  timeit(set_insert, "insert");
  timeit(set_emplace, "emplace");
}

出力例:

638.45  ms for insert
619.44  ms for emplace
609.43  ms for insert
652.55  ms for emplace

[編集] 関連項目

ヒントを使用して要素をその場で構築します
(パブリックメンバ関数) [edit]
要素またはノード (C++17以上)を挿入します
(パブリックメンバ関数) [edit]