To get the last N items from a vector in C++, you can use array slicing in combination with the size of the vector.
In this example,
#include <iostream>
#include <vector>
int main() {
// Define a vector containing elements
std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Specify the number of items to retrieve (N)
int N = 5;
// Calculate the starting index for the last N items
int start_index = vec.size() - N;
// Retrieve the last N items from the vector using array slicing
std::vector<int> last_N_items(vec.begin() + start_index, vec.end());
// Print the last N items
std::cout << "[ ";
for (int i : last_N_items) {
std::cout << i << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[6 7 8 9 10]
In this example,
#include <iostream>
#include <vector>
#include <string>
int main() {
// Define a vector containing strings
std::vector<std::string> stringVector = {"apple", "banana", "orange", "grape", "kiwi"};
// Calculate the starting index for the last three items
int start_index = stringVector.size() - 3;
// Retrieve the last three items from the string vector using array slicing
std::vector<std::string> lastThreeItems(stringVector.begin() + start_index, stringVector.end());
// Print the last three items
std::cout << "[ ";
for (const std::string& str : lastThreeItems) {
std::cout << str << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[orange banana apple ]
In this tutorial, we learned How to get Last N Items from a Vector in C++ language with well detailed examples.