Namespaces
Variants

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

From cppreference.net

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

若容器中尚不存在具有该键的元素,则使用给定的 args 在容器内就地构造一个新元素并插入。

新元素的构造函数将以与传递给 emplace 完全相同的参数被调用,这些参数通过 std:: forward < Args > ( args ) ... 进行转发。 即使容器中已存在具有相同键的元素,新元素仍会被构造,在这种情况下新构造的元素将立即被销毁。

如果 value_type 不能通过 args 实现 EmplaceConstructible set 中,则行为未定义。

不会使任何迭代器或引用失效。

目录

参数

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

返回值

一个由指向插入元素(或阻止插入的元素)的迭代器和一个 bool 值组成的对,当且仅当插入成功时该布尔值被设置为 true

异常

若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。

复杂度

与容器大小呈对数关系。

注释

谨慎使用 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

另请参阅

使用提示原位构造元素
(公开成员函数)
插入元素 或节点 (since C++17)
(公开成员函数)