std::set<Key,Compare,Allocator>:: emplace
|
template
<
class
...
Args
>
std:: pair < iterator, bool > emplace ( Args && ... args ) ; |
(C++11부터)
(C++26부터 constexpr) |
|
컨테이너에 동일한 키를 가진 요소가 없을 경우, 주어진 args 로 제자리에서 생성된 새 요소를 삽입합니다.
새로운 요소의 생성자는
emplace
에 제공된 인자와 정확히 동일한 인자로 호출되며,
std::
forward
<
Args
>
(
args
)
...
를 통해 전달됩니다.
컨테이너에 해당 키를 가진 요소가 이미 존재하는 경우에도 요소가 생성될 수 있으며, 이 경우 새로 생성된 요소는 즉시 파괴됩니다.
만약
value_type
이
EmplaceConstructible
가 아니어서
set
에
args
로부터 생성될 수 없는 경우, 동작은 정의되지 않습니다.
반복자나 참조가 무효화되지 않습니다.
목차 |
매개변수
| args | - | 요소의 생성자에 전달할 인수들 |
반환값
삽입된 요소(또는 삽입을 방해한 요소)에 대한 반복자와 삽입이 발생한 경우에만 bool 값이 true 로 설정된 쌍입니다.
예외
어떤 이유로든 예외가 발생하면, 이 함수는 아무런 효과를 가지지 않습니다( strong exception safety guarantee ).
복잡도
컨테이너 크기에 대해 로그 시간 복잡도를 가집니다.
참고 사항
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
참고 항목
|
(C++11)
|
힌트를 사용하여 제자리에서 요소를 생성합니다
(public member function) |
|
요소를 삽입합니다
또는 노드를 삽입합니다
(since C++17)
(public member function) |