BeeBand
BeeBand

Reputation: 11483

Is it possible to return an iterator as an index?

For example, if I use std::find_if like this:

std::vector<Rect>::iterator it = 
  std::find_if(regions.begin(), regions.end(), find_region(x,y));

Can I get the index of the iterator it in a straightforward way?

Upvotes: 2

Views: 210

Answers (4)

Stewart
Stewart

Reputation: 4044

Vector iterators are random access, so you can simply use

it - regions.begin()

but std::distance works on a wider variety of iterator types.

Upvotes: 1

Achille
Achille

Reputation: 111

Use std::distance(). Ensure you don't accidentally invalidate the iterator by modifying the vector in between, though.

Upvotes: 1

Nick Meyer
Nick Meyer

Reputation: 40272

Try std::distance(regions.begin(), it) from the <iterator> header file.

Upvotes: 8

Related Questions