Initialize Vector in C++
A vector in C++ is a sequence container that stores elements of the same data type in contiguous memory locations. It is an implementation of the dynamic array concept. There are several ways to initialize a vector in C++.
Syntax
vector<datatype> vector_name = {element1, element2, ..., elementN};
vector<datatype> vector_name(N, value);
Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Initialize vector using initializer list
vector<int> v1 = {1, 2, 3, 4, 5};
for (int i : v1) {
cout << i << " ";
}
cout << endl;
// Initialize vector using fill constructor
vector<int> v2(5, 10); // vector of size 5 with each element initialized to 10
for (int i : v2) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output
1 2 3 4 5
10 10 10 10 10
Explanation
In the above example, we have initialized two vectors using two different methods.
- The first vector (v1) is initialized using an initializer list of five integers.
- The second vector (v2) is initialized using a fill constructor, which creates a vector of a specified size with each element initialized to a specified value.
Use
Vector initialization is useful when initializing a vector with pre-defined elements. This can save time when creating large vectors or when dealing with a large number of pre-defined elements.
vector<string> names = {"Alice", "Bob", "Charlie", "David"};
In the above example, we have initialized a vector of strings using an initializer list. This allows us to create a vector with a pre-defined list of names.
Important Points
- Vectors can be initialized using an initializer list or a fill constructor.
- Using an initializer list is useful when creating a vector with a pre-determined list of elements.
- Using a fill constructor is useful when creating a vector of a specified size with each element initialized to a specified value.
Summary
In summary, initializing a vector in C++ can be done using an initializer list or a fill constructor. This is useful for creating vectors with pre-defined elements or vectors of a specified size with each element initialized to a specified value.