To get a sublist in C++ using std::list
, you can use iterators to specify the range of elements.
In this example,
myList
with some elements.#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
auto start = std::next(myList.begin(), 1);
auto end = std::next(myList.begin(), 4);
std::list<int> subList(start, end);
std::cout << "Sublist: ";
for (int val : subList) {
std::cout << val << " ";
}
return 0;
}
Sublist: 2 3 4
In this example,
myList
with some elements.#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50, 60};
auto start = std::next(myList.begin(), 2);
auto end = std::next(myList.begin(), 5);
std::list<int> subList(start, end);
std::cout << "Sublist: ";
for (int val : subList) {
std::cout << val << " ";
}
return 0;
}
Sublist: 30 40 50
In this tutorial, we learned How to get Sub List in C++ language with well detailed examples.