initialize vector c++
To initialize a vector in C++, you can follow these steps:
- Declare a vector variable: Start by declaring a variable of type vector. You need to specify the type of elements the vector will hold. For example, to create a vector of integers, you would declare it as follows:
cpp
std::vector<int> myVector;
- Initialize the vector with values: You can initialize the vector with a set of initial values using the initializer list syntax. The values are enclosed in curly braces and separated by commas. For example, to initialize a vector of integers with the values 1, 2, and 3, you would do the following:
cpp
std::vector<int> myVector = {1, 2, 3};
- Add elements to the vector: If you don't know the initial values at the time of declaration, you can add elements to the vector using the
push_back()
function. This function adds elements to the end of the vector. For example, to add the values 4, 5, and 6 to the vector, you would use the following code:
cpp
std::vector<int> myVector;
myVector.push_back(4);
myVector.push_back(5);
myVector.push_back(6);
- Accessing elements of the vector: To access the elements of the vector, you can use the subscript operator
[]
or theat()
function. The subscript operator provides direct access to the elements, while theat()
function performs bounds checking and throws an exception if the index is out of range. For example, to access the first element of the vector, you can use the following code:
cpp
int firstElement = myVector[0];
- Getting the size of the vector: To get the number of elements in the vector, you can use the
size()
function. It returns the number of elements in the vector as an unsigned integer. For example, to get the size of the vector, you would use the following code:
cpp
unsigned int vectorSize = myVector.size();
These steps should help you initialize and work with vectors in C++.