To append an element to a list in C++ using std::list
, you can use the push_back
method.
In this example,
and
.std::list
named numbers
with initial integer values.push_back
method of the std::list
numbers
to append a new integer to the list.push_back
method modifies the original list by adding the new element at the end.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4};
numbers.push_back(5);
std::cout << "Updated list: ";
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}
Updated list: 1 2 3 4 5
In this example,
and
.std::list
named numbers
with initial integer values.std::list
named new_elements
containing elements to be appended.insert
method to add all elements from new_elements
to the end of numbers
.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4};
std::list<int> new_elements = {5, 6, 7};
numbers.insert(numbers.end(), new_elements.begin(), new_elements.end());
std::cout << "Updated list: ";
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}
Updated list: 1 2 3 4 5 6 7
In this tutorial, we learned How to Append an Element to a List in C++ language with well detailed examples.