Reputation: 27544
I'm trying to get the index of an iterator of a list, I've read this stackoverflow question and tried the following code:
std::list<int> v;
std::list<int>::iterator iter = v.insert(v.begin(), 1);
int i = iter - v.begin();
Surprisingly it doesn't work, I got an error.
error: invalid operands to binary expression
What's the problem? How to make it work?
Upvotes: 2
Views: 241
Reputation: 36463
v.insert
returns a list iterator, that list iterator only satisfies BiDirectionalIterator. That means that operator-
isn't defined for it.
To get the distance you can use std::distance
instead:
int diff = std::distance(v.begin(), iter);
Upvotes: 3
Reputation: 37488
List container iterators are not random access iterators and therefore don't provide substration. You can use std::distance
to obtain index.
Upvotes: 3