how to append to a vector c++
Certainly! Here's an example of appending elements to a vector in C++:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Appending a single element to the vector
numbers.push_back(6);
// Appending multiple elements using initializer list
numbers.insert(numbers.end(), {7, 8, 9});
// Displaying the elements in the vector after appending
std::cout << "Updated Vector: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
#include <vector>
: This line includes the header file necessary for using vectors in C++.std::vector<int> numbers = {1, 2, 3, 4, 5};
: This creates a vector namednumbers
and initializes it with five integer elements.numbers.push_back(6);
: This appends a single element (6 in this case) to the end of the vector using thepush_back
method.numbers.insert(numbers.end(), {7, 8, 9});
: Here, multiple elements (7, 8, and 9) are appended to the vector using theinsert
method.numbers.end()
signifies the position in the vector to insert the new elements, in this case, at the end of the vector.The
for
loop iterates through the elements in the vectornumbers
and prints them to the console, displaying the updated contents of the vector after appending the elements.return 0;
: This line indicates the end of themain()
function and signifies successful program execution.