본문 바로가기

SW 지식/C 와 C++ 공부

[C++] emplace 함수

emplace의 사전적 정의

emplace

타동사
1. 설치하다
2. 관입하다
3. 발달하다

이처럼 emplace 함수는, C++11부터 들어간 함수로, push() 함수와 비슷한 기능을 합니다. ("Insert a new element")

지난 게시물에서 배운, std::unordered_map 뿐만 아니라, std::vector 에도 있는 함수였습니다!
이 페이지에선 unordered_map의 emplace() 함수로 설명 및 예시를 들어보겠습니다.

Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container.
Careful use of emplace allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element (i.e. std::pair<const Key, T>) is called with exactly the same arguments as supplied to emplace, forwarded via std::forward<Args>(args).... The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately.

emplace() 함수는, 해당 키의 element가 없으면, 지정된 argument로 정해진 자리에 새로운 element를 삽입합니다.
emplace를 사용하면, 불필요한 복사나 이동 작업을 피하며 새로운 element를 생성할 수 있습니다.
만약 container에 해당 키의 element가 이미 존재하는 경우에도 생성되지만, 이러한 경우 새로 생성된 element는 바로 소멸됩니다.

그리고 삽입이 이뤄졌을 때, container의 `size()` 크기가 하나 증가됩니다.
비슷한 멤버 함수로는 `insert()`가 있습니다.


사용 예시를 한 번 살펴보겠습니다.

#include <iostream>
#include <utility>
#include <string>
#include <unordered_map>
 
int main()
{
    std::unordered_map<std::string, std::string> myMap;
 
    // uses pair's move constructor
    myMap.emplace(std::make_pair(std::string("a"), std::string("a")));
 
    // uses pair's converting move constructor
    myMap.emplace(std::make_pair("b", "abcd"));
 
    // uses pair's template constructor
    myMap.emplace("d", "ddd");
 
    // uses pair's piecewise constructor
    myMap.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // as of C++17, myMap.try_emplace("c", 10, 'c'); can be used
 
    for (const auto &iter : myMap) 
    {
        std::cout << iter.first << " => " << iter.second << '\n';
    }
}

emplace() 함수에 넣을 수 있는 key와 value를 다양하게 사용해 보았는데요.
"d"처럼 std::string 을 직접 넣어도 되고, std::make_pair()을 통해 쌍을 만들 수도 있습니다.

이렇게 하였을 때, 결과는 다음과 같습니다.

a => a
b => abcd
c => cccccccccc
d => ddd

끝 :)

 

참조 1) https://www.cplusplus.com/reference/unordered_map/unordered_map/emplace/

참조 2) https://en.cppreference.com/w/cpp/container/unordered_map/emplace