Junior — Middle
Is it possible to use the emplace_back function with std::vector without passing arguments?
sobes.tech AI
Answer from AI
Yes, the emplace_back function of std::vector can be called without passing arguments if the element type in the vector has a default constructor. In this case, a new element will be created, initialized by the default constructor.
Example:
#include <vector>
#include <iostream>
struct Point {
int x = 0, y = 0;
Point() = default; // default constructor
};
int main() {
std::vector<Point> points;
points.emplace_back(); // will create a Point with x=0, y=0
std::cout << points[0].x << ", " << points[0].y << std::endl; // Outputs: 0, 0
}
If the type does not have a default constructor, then calling emplace_back() without arguments will result in a compilation error.