名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | set
 
 
 
 
template< class... Args >
std::pair<iterator, bool> emplace( Args&&... args );
(C++11 起)

若容器中不存在鍵值與給定 args 所構造的元素相同的元素,則將新元素就地構造並插入容器。

新元素的建構函式被呼叫,其引數與提供給 `emplace` 的引數完全相同,並透過 std::forward<Args>(args)... 轉發。即使容器中已經存在具有該鍵的元素,該元素也可能被構造,在這種情況下,新構造的元素將立即被銷燬。

謹慎使用 emplace 允許構造新元素,同時避免不必要的複製或移動操作。

迭代器或引用均未失效。

目錄

[編輯] 引數

args - 轉發給元素建構函式的引數

[編輯] 返回值

一個由指向插入元素的迭代器(或阻止插入的元素)和布林值組成的對,當且僅當插入發生時,該布林值設定為 true

[編輯] 異常

如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。

[編輯] 複雜度

容器大小的對數級別。

[編輯] 示例

#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 起)
(公共成員函式) [編輯]