ggrr
ggrr

Reputation: 7867

How to know if the element is last element in vector using for(int i:myVector) code style?

for(int& i:myVector){
   ...
}

is there any method to know if i is the last element using this code style without using extra variables or methods (e.g.:count,myVector.size())?

like

for(vector<int>::iterator it=myVector.begin();it!=myVector.end();++it){
    if(it!=end()-1){
        ...
    }
}

Upvotes: 0

Views: 175

Answers (1)

vsoftco
vsoftco

Reputation: 56567

The answer is NO, there is no way of finding out the index without using an auxiliary count. The range-based notation is hiding the index from you and gives you the dereferenced iterator. The range-based for is equivalent to (from cppreference):

{
    auto && __range = range_expression ; 
    for (auto __begin = begin_expr,
    __end = end_expr; 
    __begin != __end; ++__begin) { 
        range_declaration = *__begin; 
        loop_statement 
    } 
} 

If you need index-based access, then use plain old iterators.

Upvotes: 2

Related Questions