To slice a list in C++, you can use iterators and the std::advance
function to specify the start and end positions.
In this example,
numbers
with integer values.std::advance
function to advance the iterators to the desired positions.slicedNumbers
using the iterators.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
auto start = numbers.begin();
auto end = numbers.begin();
std::advance(start, 1);
std::advance(end, 4);
std::list<int> slicedNumbers(start, end);
for (int num : slicedNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
2 3 4
In this example,
words
with string values.std::advance
function to advance the iterators to the desired positions.slicedWords
using the iterators.#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<std::string> words = {"apple", "banana", "cherry", "date", "elderberry"};
auto start = std::next(words.begin(), 1);
auto end = std::next(words.begin(), 4);
std::list<std::string> slicedWords(start, end);
for (const std::string& word : slicedWords) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
banana cherry date
In this tutorial, we learned How to Slice a List in C++ language with well detailed examples.