std::multiset<Key,Compare,Allocator>::emplace
template< class... Args > iterator emplace( Args&&... args ); | (с C++11) |
Вставляет новый элемент в контейнер, созданный на месте с заданными args.
Аккуратное использование emplace позволяет создать новый элемент, избегая ненужных копирования или перемещения. Конструктор нового элемента вызывается с ровно теми же аргументами, что и предоставлены в emplace, переданными через std::forward<Args>(args)....
Ни один итератор или ссылка не становятся недействительными.
Параметры
| args | - | аргументы для передачи конструктору элемента |
Возвращаемое значение
Возвращает итератор на вставленный элемент.
Исключения
Если возникает исключение по любой причине, эта функция не имеет эффекта (гарантия прочной безопасности от исключений).
Сложность
Логарифмическая по размеру контейнера.
Пример
#include <chrono>
#include <cstddef>
#include <functional>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
class Dew
{
private:
int a;
int b;
int 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) | создает элементы на месте, используя подсказку (общедоступный член-функция) |
| вставляет элементы или узлы(с C++17) (общедоступный член-функция) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/container/multiset/emplace