You can increment a counter and break the loop when the desired count is reached.
Something like:
void func(const std::vector<int> & v, std::size_t n)
{
std::size_t count(0);
for(int e : v)
{
if(count < n)
{
std::cout << e << " "; // Do what you want with e.
++count;
}
else
break; // Exit the loop
}
}
But I would not recommend doing it. Range-based for loops are meant to iterate over the whole container.
The above solution is thus a less readable way of simply doing:
void func(const std::vector<int> & v, std::size_t n)
{
for(std::size_t i = 0; (i < v.size()) && (i < n); ++i)
{
std::cout << v[i] << " "; // Do what you want with v[i].
}
}
Or also:
void func(const std::vector<int> & v, std::size_t n)
{
std::size_t count(0);
for(std::vector<int>::const_iterator cit = v.cbegin(); (cit != v.cend()) && (count < n); ++cit, ++count)
{
std::cout << *cit << " "; // Do what you want with *cit
}
}
arr) is passed by value and changes to it won't be visible to the calluer, simply resize based onn, and then use a range-based loopfor (int i: arr)...as usual. Otherwise, it is not possible to use a range-based for as you wish.for (int i=0; i<n; i++) std::cout << arr[i] << "\n";?