To slice the first N elements from a list in C++, you can use iterators and the std::advance
function to specify the end position.
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};
int n = 3;
auto end = numbers.begin();
std::advance(end, n);
std::list<int> slicedNumbers(numbers.begin(), end);
for (int num : slicedNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Sliced list: 1 2 3
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"};
int n = 2;
auto end = words.begin();
std::advance(end, n);
std::list<std::string> slicedWords(words.begin(), end);
for (const std::string& word : slicedWords) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
Sliced list: apple banana
In this tutorial, we learned How to Slice First N Elements from a List in C++ language with well detailed examples.