命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | set
 
 
 
 
template< class... Args >
std::pair<iterator, bool> emplace( Args&&... args );
(since C++11)

如果容器中没有具有该键的元素,则将使用给定的 args 就地构造的新元素插入到容器中。

新元素的构造函数使用与提供给 emplace 的参数完全相同的参数调用,并通过 std::forward<Args>(args)... 转发。即使容器中已经存在具有该键的元素,也可能会构造元素,在这种情况下,新构造的元素将立即销毁。

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

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

目录

[edit] 参数

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

[edit] 返回值

一个由指向插入元素的迭代器(或阻止插入的元素的迭代器)和一个 bool 值组成的pair,如果且仅当发生插入时,该值设置为 true

[edit] 异常

如果由于任何原因抛出异常,则此函数不起作用(强异常安全保证)。

[edit] 复杂度

对容器大小呈对数。

[edit] 示例

#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

[edit] 参见

使用提示就地构造元素
(公共成员函数) [编辑]
插入元素 或节点(C++17 起)
(公共成员函数) [编辑]