To append an item to a vector in C++, you can use the push_back()
method provided by the std::vector
class. This method allows you to add elements to the end of the vector dynamically.
In this example,
<vector>
header to use the vector class.std::vector
class template.push_back()
method on the vector to add the new integer to the end of the vector.#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
int newNumber = 10;
numbers.push_back(newNumber);
for (int i : numbers) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
10
In this example,
<vector>
header to use the vector class.std::vector
class template.push_back()
method on the vector to add the new string to the end of the vector.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words;
std::string newWord = "Hello";
words.push_back(newWord);
for (std::string word : words) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
Hello
In this tutorial, we learned How to Append an Item to a Vector in C++ language with well detailed examples.