Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Range-looping vector from the second element?

I have a std::vector<std::string> v; (initialized). How can I use the range-for loop for accessing all elements except the first one (on index zero). For all elements:

for (const string & s: v)
    process(s);

Instead of the v a range expression can be used. How can I write the range expression to skip the first element (or skip the first n elements)?

I know how to get the effect using v.begin() + 1 and using the classic loop. I am searching for the new, more readable, recommended alternative to do that. Possibly something similar to Python slicing? ...like:

for s in v[1:]:
    process(s)
like image 599
pepr Avatar asked Aug 11 '15 08:08

pepr


People also ask

How do you access vector elements in a for loop?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .

Does C have range-based for loops?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.


1 Answers

Until ranges make it into the standard library, you won't get any better than a vanilla for loop in plain C++ :

for(auto i = begin(v) + 1, e = end(v); i !=e; ++i)
    // Do something with *i
like image 113
Quentin Avatar answered Sep 25 '22 15:09

Quentin