To split a list in C++ using std::list
, you can iterate through the list and create sublists manually.
In this example,
and
.std::list
named numbers
with initial integer values.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};
int chunkSize = 3;
std::list<std::list<int>> chunks;
auto it = numbers.begin();
while (it != numbers.end()) {
std::list<int> chunk;
for (int i = 0; i < chunkSize && it != numbers.end(); ++i) {
chunk.push_back(*it);
++it;
}
chunks.push_back(chunk);
}
for (const auto& sublist : chunks) {
for (int num : sublist) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
1 2 3 4 5 6 7 8
In this example,
and
.std::list
named numbers
with initial integer values.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};
int chunkSize = 3;
std::list<std::list<int>> chunks;
auto it = numbers.begin();
while (it != numbers.end()) {
std::list<int> chunk(it, std::next(it, chunkSize));
chunks.push_back(chunk);
std::advance(it, chunkSize);
}
for (const auto& sublist : chunks) {
for (int num : sublist) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
1 2 3 4 5 6 7 8
In this tutorial, we learned How to Split a List in C++ language with well detailed examples.