To slice the last N elements from a list in C++, you can use reverse iterators along with the std::list
container.
In this example,
numbers
with integer values.std::advance
function to position the iterators at the beginning of the slice.slicedNumbers
using the reverse iterators.#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
int n = 3;
auto it = numbers.rbegin();
std::advance(it, n);
std::list<int> slicedNumbers(numbers.rbegin(), it);
for (int num : slicedNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Sliced list: 3 2 1
In this example,
words
with string values.std::advance
function to position the iterators at the beginning of the slice.slicedWords
using the reverse iterators.#include <iostream>
#include <list>
#include <iterator>
#include <string>
int main() {
std::list<std::string> words = {"apple", "banana", "cherry", "date", "elderberry"};
int n = 2;
auto it = words.rbegin();
std::advance(it, n);
std::list<std::string> slicedWords(words.rbegin(), it);
for (const std::string& word : slicedWords) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
Sliced list: date cherry
In this tutorial, we learned How to Slice Last N Elements from a List in C++ language with well detailed examples.