C++에서
emplace()
와insert()
메서드는 둘 다set
자료구조에 원소를 넣는 기능을 가진다.
emplace()
메서드는set
에 새로운 원소를 생성하여 집어 넣으면서 어떤 임시 오브젝트를 생성하지 않는다.
반면에insert()
는set
에 한 원소의 복사본을 집어넣는 메서드로emplace()
메서드에 비해 원소의 복사 과정이 필요하기 때문에 속도가 더 느리다.
아래는 두 메서드의 예시를 비교하였다.
#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> mySet;
// Example using emplace()
mySet.emplace("foo"); // Construct the element "foo" in-place
mySet.emplace("bar"); // Construct the element "bar" in-place
mySet.emplace("baz"); // Construct the element "baz" in-place
// Example using insert()
std::string qux = "qux";
mySet.insert(qux); // Copy the string "qux" and insert the copy
std::string quux = "qux";
mySet.insert(quux); // Copy the string "qux", but do not insert the copy
// because it is already in the set
// Print the contents of the set
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}