How do I use emplace vs push with std::array?

In C++, the `std::array` is a container that encapsulates fixed-size arrays. It is part of the standard library and provides a similar interface to other container types in C++. When working with `std::array`, you might come across two methods for adding elements: `push_back` and `emplace`. However, it's important to note that `std::array` does not support `push_back` because its size is fixed at compile time. Instead, you can use `emplace` in certain scenarios, but it is more commonly leveraged with other dynamic containers like `std::vector`.

The primary difference is that `emplace` constructs an element in place, meaning that it can efficiently create an object directly within the container without the need for an additional copy or move. In contrast, for fixed-size containers like `std::array`, you generally initialize the elements at the point of declaration or assignment.

Using std::array

Since `std::array` has a fixed size, you typically do not use `emplace` or `push`. Instead, you define the type and size at compile time.


#include <array>
#include <iostream>

int main() {
    std::array myArray = {1, 2, 3};

    // Accessing elements
    std::cout << "First element: " << myArray[0] << std::endl;

    // You can use emplace with std::vector instead
    // std::vector myVector;
    // myVector.emplace_back(4); // This is how you would use emplace

    return 0;
}
    

C++ std::array push_back emplace fixed-size array standard library