The push_back() function in C++ STL is used to insert a new element into a vector while automatically managing its storage requirements.
- Inserts an element at the end of the vector.
- Automatically reallocates memory when additional capacity is required.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6};
// Add an element at the end of the vector
v.push_back(9);
for (int i : v)
cout << i << " ";
return 0;
}
Output
1 4 6 9
Explanation: The element 9 is inserted at the end of the vector, increasing its size from 3 to 4.
Syntax
The vector push_back() is a member method of the std::vector class defined inside the <vector> header file.
v.push_back(val);
Parameters: val - rlement to be added to the vector at the end.
Return Value: this function does not return any value.
Working of vector::push_back()
The push_back() function appends the new element to the end of the vector. Its behavior depends on the current capacity of the vector:
- If sufficient capacity is available, the element is inserted directly at the end.
- If the vector has reached its capacity, it allocates a larger memory block.
- The existing elements are moved or copied, and the new element is inserted.
Examples of vector::push_back()
The following examples demonstrate different use cases of the push_back() function.
Example 1: Initializing an Empty Vector
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
// Add elements to the vector
v.push_back(3);
v.push_back(7);
v.push_back(9);
for (int i : v)
cout << i << " ";
return 0;
}
Output
3 7 9
Explanation: Elements are inserted one by one into an initially empty vector.
Example 2: Adding Elements to a Vector of Strings
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> v = {"Hello", "Geeks"};
// Add string to the vector
v.push_back("Welcome");
for (string s: v)
cout << s << " ";
return 0;
}
Output
Hello Geeks Welcome
Explanation: The string "Welcome" is appended to the end of the vector.
Example 3: Adding Elements Inside a Loop
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
for (int i = 1; i <= 5; i++)
v.push_back(i * 10);
for (int x : v)
cout << x << " ";
return 0;
}
Output
10 20 30 40 50
Explanation: push_back() is commonly used to dynamically build a vector during program execution.
Key Features of vector::push_back()
The following points highlight the important characteristics and behavior of the push_back() function:
- push_back() always inserts the new element at the end of the vector.
- The size of the vector increases by one after each successful insertion.
- The vector automatically reallocates memory when its current capacity is exhausted.
- It can be used with vectors storing any data type, including user-defined classes and objects.