In C++, vectors are dynamic arrays, that can grow or shrink and their storage is handled by the container itself. There are two ways of inserting an element in a vector. They are push_back() and emplace_back(). In this article, we will discuss the difference between them.
This method is used to insert elements in a vector from the end of the container. As the flexibility in the size of the vector is dynamic, the size of the container also increased by 1 after inserting any new element.
Copied Copied Copied Copied Copied Copied
- In the main function, a vector of class GFG is created of size is 1. Before inserting the first GFG object into the array, it is created using a parameterized constructor, and since the vector is of type GFG, the object is passed to the “GFG” copy constructor, hence “Copied” is printed once. But when another element is to be inserted, a new vector of size greater than the previous one is created, then the “first” element, is again copied, and then the second object is created and copied, hence “Copied” is printed twice, upon execution.
- Similarly, when the third object is to be created, a new vector of greater size is allocated in memory, the first element is copied, then the second element is copied, and then the third element is copied. Hence, “Copied” is printed thrice as the copy constructor is called thrice, once for each element inserted.
- However, if the size of the vector is fixed, then before inserting any element, the number of times “Copied” will be printed is one. This is because as the required size is declared, no re-copying of elements takes place upon each insertion.
Note: reserve() is used instead of using “vector<Point> vertices(3)”, as the below syntax sometimes doesn’t work because there is no default constructor defined in the class.
The cost due to the copying of elements is high. Below is the program to optimize the usage of C++ Vectors to reduce the cost of copying elements:
Copied Copied Copied
This method is used instead of creating the object using parameterized constructor and allocating it into a different memory, then passing it to the copy constructor, which will insert it into the vector. This function can directly insert the object without calling the copy constructor. Below is the program to illustrate the same:
Explanation: In the above program nothing is printed as the copying of the constructor doesn’t take place while using the emplace_back() function.