📜  emplace vs push c++ (1)

📅  最后修改于: 2023-12-03 15:00:36.008000             🧑  作者: Mango

Emplace vs Push in C++

When working with containers in C++, we often need to insert new elements into them. Two common methods for inserting elements into a container are emplace() and push_back() (or push_front() for some containers). In this article, we'll explore the differences between these methods and when to use each.

push_back() and push_front()

push_back() and push_front() are methods available for sequential containers such as vector, deque, and list. These methods allow us to insert an element at the end or at the beginning of the container, respectively.

#include <vector>

std::vector<int> v{1, 2, 3};

// Inserts 4 at the end of the vector
v.push_back(4);

// Inserts 0 at the beginning of the vector
v.push_front(0);
emplace()

emplace() is a method that allows us to construct and insert an object in-place. Unlike push_back() and push_front(), emplace() does not require the object to be copied or moved into the container. Instead, emplace() constructs the object directly in the container, using the arguments provided.

#include <vector>

struct Person {
    std::string name;
    int age;
};

std::vector<Person> v;

// Constructs a Person object in-place and inserts it into the vector
v.emplace_back("Alice", 25);

// The following line would not compile, since Person does not have a default constructor
// v.emplace_back();

In the example above, emplace_back() constructs a Person object with the name "Alice" and age 25 in-place in the vector. This avoids the need to create a temporary Person object and move it into the vector.

When to use emplace() vs push_back()

In general, we should prefer emplace() over push_back() if possible, since it can be more efficient. emplace() avoids unnecessary copying or moving of objects into the container, and can be faster if the object is expensive to copy or move. However, emplace() requires the object to be constructible in place, which may not always be possible. In such cases, we should use push_back() instead.

It's also worth noting that emplace() is only available for containers that support in-place construction, such as vector, deque, list, set, and map. For other containers, we must use push_back() or push_front() to insert elements.

Conclusion

In summary, emplace() and push_back() (or push_front()) are two methods for inserting elements into containers in C++. emplace() allows us to construct an object in-place and insert it into the container, while push_back() and push_front() copy or move the object into the container. We should prefer emplace() over push_back() if possible, but use push_back() if in-place construction is not possible.