首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::set::emplace

template< class... Args > std::pair<iterator,bool> emplace( Args&&... args );

?

(since C++11)

将一个新元素插入到在给定的容器中构造的容器中。args如果容器中没有带键的元素。

谨慎使用emplace允许构造新元素,同时避免不必要的复制或移动操作。调用新元素的构造函数的参数与提供给emplace,通过std::forward<Args>(args)...即使容器中已经有一个带有密钥的元素,也可以构造该元素,在这种情况下,新构造的元素将立即被销毁。

没有迭代器或引用无效。

参数

args

-

arguments to forward to the constructor of the element

返回值

返回由迭代器组成的一对插入元素,如果没有插入,则返回已经存在的元素,并返回bool表示插入是否发生。插入为true,无插入为false。

例外

如果任何操作引发异常,则此函数没有任何效果。

复杂性

容器大小的对数。

二次

代码语言:javascript
复制
#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");
}

二次

可能的产出:

二次

代码语言:javascript
复制
638.45  ms for insert
619.44  ms for emplace
609.43  ms for insert
652.55  ms for emplace

二次

另见

emplace_hint (C++11)

constructs elements in-place using a hint (public member function)

insert

inserts elements or nodes (since C++17) (public member function)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com