initialise a vector c++
To initialize a vector in C++, you can follow the steps below:
Include the necessary header file: Begin by including the
header file, which provides the vector container class. Declare the vector: Declare a vector variable with a specific data type. For example, to declare a vector of integers, you can write:
cpp
std::vector<int> myVector;
- Initialize the vector: You can initialize the vector with a set of values using different methods. Here are a few examples:
a. Using the initializer list:
```cpp
std::vector<int> myVector = {1, 2, 3, 4, 5};
```
b. Using the constructor and fill method:
```cpp
std::vector<int> myVector(5, 0); // Creates a vector of size 5 with all elements initialized to 0
```
c. Using the push_back method:
```cpp
std::vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
```
- Access and modify vector elements: You can access and modify individual elements of the vector using the subscript operator ([]). For example:
cpp
int firstElement = myVector[0]; // Access the first element
myVector[1] = 10; // Modify the second element
- Iterate over the vector: You can use a loop (such as a for loop or a range-based for loop) to iterate over the vector elements. Here's an example using a range-based for loop:
cpp
for (int element : myVector) {
// Do something with each element
}
- Get the size of the vector: You can use the
size()
member function to get the current size of the vector. For example:
cpp
std::cout << "Size of vector: " << myVector.size() << std::endl;
Remember to include the necessary header file, declare the vector with a specific data type, initialize it with values, access and modify its elements as needed, iterate over the vector, and use the size()
member function to get its size. These steps can be modified and expanded based on your specific requirements.