How to Create Vector in C++: Syntax and Examples
In C++, you create a vector by including the
<vector> header and declaring a vector with std::vector<Type> name;. This creates a dynamic array that can grow or shrink as needed.Syntax
To create a vector in C++, you first include the <vector> header. Then declare a vector with the syntax:
std::vector<Type> name;- creates an empty vector of the specified type.std::vector<Type> name(size);- creates a vector with a fixed size, initialized with default values.std::vector<Type> name(size, value);- creates a vector with a fixed size, initialized with the given value.
cpp
#include <vector> // Create an empty vector of integers std::vector<int> numbers; // Create a vector of 5 integers, default initialized to 0 std::vector<int> zeros(5); // Create a vector of 3 integers, each initialized to 7 std::vector<int> sevens(3, 7);
Example
This example shows how to create a vector, add elements, and print them.
cpp
#include <iostream> #include <vector> int main() { std::vector<int> numbers; // empty vector numbers.push_back(10); // add 10 numbers.push_back(20); // add 20 numbers.push_back(30); // add 30 std::cout << "Vector elements:" << std::endl; for (int num : numbers) { std::cout << num << std::endl; } return 0; }
Output
Vector elements:
10
20
30
Common Pitfalls
Common mistakes when creating vectors include:
- Forgetting to include
<vector>header. - Not using
std::prefix or missingusing namespace std;. - Trying to access elements without adding any, causing out-of-range errors.
- Confusing vector size with capacity.
cpp
#include <vector> #include <iostream> int main() { // Wrong: no elements added, accessing index 0 causes error std::vector<int> v; // std::cout << v[0]; // This is unsafe and may crash // Right: add elements before accessing v.push_back(5); std::cout << v[0] << std::endl; // prints 5 return 0; }
Output
5
Quick Reference
| Syntax | Description |
|---|---|
| std::vector | Create empty vector of Type |
| std::vector | Create vector with size, default values |
| std::vector | Create vector with size, initialized to value |
| name.push_back(value); | Add value to end of vector |
| name.size(); | Get number of elements in vector |
| name[index]; | Access element at index (0-based) |
Key Takeaways
Include and use std::vector to create vectors in C++.
Vectors are dynamic arrays that can grow with push_back().
Always add elements before accessing to avoid errors.
Use vector.size() to get the current number of elements.
Remember to use the std:: prefix or a using directive.