Wa0030.
Wa0030.
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector
can grow dynamically.
That is, we can change the size of the vector during the execution of a program as per our requirements.
Vectors are part of the C++ Standard Template Library. To use vectors, we need to include
the vector header file in our program.
#include <vector>
int main() {
// initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// uniform initialization
vector<int> vector2{6, 7, 8, 9, 10};
// method 3
vector<int> vector3(5, 12);
cout << "vector1 = ";
// ranged loop
for (const int& i : vector1) {
cout << i << " ";
}
// ranged loop
for (const int& i : vector2) {
cout << i << " ";
}
// ranged loop
for (int i : vector3) {
cout << i << " ";
}
return 0;
}
Output
vector1 = 1 2 3 4 5
vector2 = 6 7 8 9 10
vector3 = 12 12 12 12 12
Here, we have declared and initialized three different vectors using three different initialization methods and
displayed their contents.
int main() {
vector<int> num {1, 2, 3, 4, 5};
return 0;
}
Output
Initial Vector: 1 2 3 4 5
Updated Vector: 1 2 3 4 5 6 7
Here, we have initialized an int vector num with the elements {1, 2, 3, 4, 5}. Notice the statements
num.push_back(6);
num.push_back(7);
Here, the push_back() function adds elements 6 and 7 to the vector.
Note: We can also use the insert() and emplace() functions to add elements to a vector.
int main() {
vector<int> num {1, 2, 3, 4, 5};
return 0;
}
Output
Element at Index 0: 1
Element at Index 2: 3
Element at Index 4: 5
Note: Like an array, we can also use the square brackets [] to access vector elements. For example,
vector<int> num {1, 2, 3};
cout << num[1]; // Output: 2
int main() {
vector<int> num {1, 2, 3, 4, 5};
return 0;
}
Output
Initial Vector: 1 2 3 4 5
Updated Vector: 1 9 3 4 7
In the above example, notice the statements,
num.at(1) = 9;
num.at(4) = 7;
Here, we have assigned new values to indexes 1 and 4. So the value at index 1 is changed to 9 and the value
at index 4 is changed to 7.
int main() {
vector<int> prime_numbers{2, 3, 5, 7};
// initial vector
cout << "Initial Vector: ";
for (int i : prime_numbers) {
cout << i << " ";
}
// final vector
cout << "\nUpdated Vector: ";
for (int i : prime_numbers) {
cout << i << " ";
}
return 0;
}
Output
Initial Vector: 2 3 5 7
Updated Vector: 2 3 5
In the above example, notice the statement,
prime_numbers.pop_back();
Here, we have removed the last element (7) from the vector.
int main() {
vector<int> num {1, 2, 3, 4, 5};
// declare iterator
vector<int>::iterator iter;
Output
num[0] = 1
num[2] = 3
num[4] = 5
int main() {
vector<int> num {1, 2, 3, 4, 5};
// declare iterator
vector<int>::iterator iter;
return 0;
}
Output
1 2 3 4 5