How to Add Element to Vector in C++: Simple Guide
To add an element to a
std::vector in C++, use the push_back() method which appends the element at the end. Alternatively, emplace_back() constructs the element in place for efficiency.Syntax
The common ways to add elements to a std::vector are:
vector.push_back(value);- Adds a copy ofvalueat the end.vector.emplace_back(args);- Constructs the element directly at the end usingargs.
Here, vector is your vector variable, and value or args are the element or constructor arguments.
cpp
std::vector<int> vec; vec.push_back(10); // Adds 10 at the end vec.emplace_back(20); // Constructs 20 at the end
Example
This example shows how to add integers to a vector using push_back and emplace_back, then prints the vector contents.
cpp
#include <iostream> #include <vector> int main() { std::vector<int> numbers; numbers.push_back(5); // Add 5 numbers.emplace_back(10); // Add 10 numbers.push_back(15); // Add 15 std::cout << "Vector elements:"; for (int num : numbers) { std::cout << ' ' << num; } std::cout << '\n'; return 0; }
Output
Vector elements: 5 10 15
Common Pitfalls
Common mistakes when adding elements to vectors include:
- Forgetting to include
<vector>header. - Using
push_backwith incompatible types causing compilation errors. - Assuming
push_backmodifies the original element instead of copying it. - Not reserving space if adding many elements, which can cause multiple reallocations.
Always ensure the element type matches the vector's type and consider reserve() for performance.
cpp
/* Wrong: pushing wrong type */ // std::vector<int> v; // v.push_back("text"); // Error: string not convertible to int /* Right: matching types */ std::vector<int> v; v.push_back(42);
Quick Reference
| Method | Description | Usage Example |
|---|---|---|
| push_back | Adds a copy of the element at the end | vec.push_back(10); |
| emplace_back | Constructs element in place at the end | vec.emplace_back(20); |
| reserve | Pre-allocates memory to avoid reallocations | vec.reserve(100); |
Key Takeaways
Use push_back() to add a copy of an element at the vector's end.
Use emplace_back() to construct an element directly in the vector for efficiency.
Ensure the element type matches the vector's type to avoid errors.
Include header and use std namespace or prefix.
Consider reserve() to improve performance when adding many elements.