The vector container is a dynamic array that can grow or shrink in size.
To use the vector container, you need to include the
Here's an example of using the vector container:
SNIPPET
1#include <iostream>
2#include <vector>
3
4int main() {
5 // Create a vector
6 std::vector<int> v;
7
8 // Add elements to the vector
9 v.push_back(10);
10 v.push_back(20);
11 v.push_back(30);
12
13 // Access elements in the vector
14 std::cout << "First element: " << v[0] << std::endl;
15 std::cout << "Size of vector: " << v.size() << std::endl;
16
17 // Modify elements in the vector
18 v[1] = 50;
19
20 // Iterate over the vector
21 std::cout << "Vector elements:" << std::endl;
22 for (int i = 0; i < v.size(); i++) {
23 std::cout << v[i] << std::endl;
24 }
25
26 return 0;
27}
In this example, we create a vector v
of type int
. We then add elements to the vector using the push_back
function. We can access elements in the vector using indexing (e.g., v[0]
for the first element). The size
function returns the number of elements in the vector. We can modify elements in the vector using indexing as well. Finally, we iterate over the vector using a for loop and print out the elements.
xxxxxxxxxx
27
int main() {
// Create a vector
std::vector<int> v;
// Add elements to the vector
v.push_back(10);
v.push_back(20);
v.push_back(30);
// Access elements in the vector
std::cout << "First element: " << v[0] << std::endl;
std::cout << "Size of vector: " << v.size() << std::endl;
// Modify elements in the vector
v[1] = 50;
// Iterate over the vector
std::cout << "Vector elements:" << std::endl;
for (int i = 0; i < v.size(); i++) {
std::cout << v[i] << std::endl;
}
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment