2

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?

Searene
  • 25,920
  • 39
  • 129
  • 186
  • Have you read the answer of the question from link mention by you? Accepted answer says it all. – Swapnil Sep 22 '18 at 13:46
  • You have the answer here: https://stackoverflow.com/questions/10564222/error-no-match-for-operator-for-list-iterator – Amit G. Sep 22 '18 at 13:54

2 Answers2

3

List container iterators are not random access iterators and therefore don't provide substration. You can use std::distance to obtain index.

user7860670
  • 35,849
  • 4
  • 58
  • 84
3

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);
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122