In this C++ tutorial, you shall learn how to append an element to the end of vector using vector::push_back() function, with example programs.
Append Element at end of Vector
To append an element to the end of vector in C++, we can use vector::push_back() method. Call push_back() method on the vector, pass the element as argument. The method appends the element at the end of the vector.
The syntax of the statement to append an element e
at the end of the vector v
is
</>
Copy
v.push_back(e);
C++ Program
In the following program, we take a string vector in fruits
, and append an element "mango"
at the end of the vector fruits
.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> fruits{ "apple", "banana", "cherry" };
fruits.push_back("mango");
for(auto& element: fruits) {
cout << element << endl;
}
}
Output
apple
banana
cherry
mango
Conclusion
In this C++ Tutorial, we learned how to append an element at the end of a vector, using push_back() method.