To get the first N items from a vector in C++, you can use the `std::vector` and iterator.
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;
// Retrieve the first N items from the vector using iterators
std::vector<int>::iterator it = vec.begin();
std::vector<int>::iterator end = vec.begin() + N;
// Print the first N items
std::cout << "[ ";
for (; it != end; ++it) {
std::cout << *it << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[ 1 2 3 4 5 ]
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"};
// Specify the range to retrieve the first three items
int range = 3;
// Retrieve the first three items from the string vector using iterators
std::vector<std::string>::iterator it = stringVector.begin();
std::vector<std::string>::iterator end = stringVector.begin() + range;
// Print the first three items
std::cout << "[ ";
for (; it != end; ++it) {
std::cout << *it << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[ apple banana orange ]
In this tutorial, we learned How to get First N Items from a Vector in C++ language with well detailed examples.