std::multiset<Key,Compare,Allocator>:: emplace
|
template
<
class
...
Args
>
iterator emplace ( Args && ... args ) ; |
(C++11 起)
(C++26 起为 constexpr) |
|
在容器中就地构造一个新元素并插入,使用给定的 args 。
新元素的构造函数将以与传递给
emplace
完全相同的参数被调用,这些参数通过
std::
forward
<
Args
>
(
args
)
...
进行转发。
如果
value_type
不能通过
args
实现
EmplaceConstructible
到
multiset
中,则行为未定义。
不会使任何迭代器或引用失效。
目录 |
参数
| args | - | 要转发给元素构造函数的参数 |
返回值
指向被插入元素的迭代器。
异常
若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。
复杂度
与容器大小呈对数关系。
注释
谨慎使用
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::multiset<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::multiset<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"); }
可能的输出:
499.61ms for cache warming... 447.89ms for insert 436.77ms for insert 430.62ms for emplace 428.61ms for emplace
另请参阅
|
(C++11)
|
使用提示原位构造元素
(公开成员函数) |
|
插入元素
或节点
(since C++17)
(公开成员函数) |