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 严格相同的实参,通过 std::forward<Args>(args)... 转发,调用新元素的构造函数。 即使容器中已有拥有该关键的元素,也可能构造元素,该情况下新构造的元素将被立即销毁。

细心地使用 emplace 允许在构造新元素的同时避免不必要的复制或移动操作。

没有迭代器或引用会失效。

参数

args - 要转发给元素构造函数的实参

返回值

由一个指向被插入元素(或指向妨碍插入的元素)的迭代器和一个当且仅当发生插入时被设为 truebool 值构成的对偶。

异常

如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。

复杂度

与容器大小成对数。

示例

#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 起)
(公开成员函数)