Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert QList iterator to index

Tags:

c++

qt

I use qLowerBound to find an item in a QList, but this function returns an iterator, while I need an index (I'll pass it to another function that expects an index). Is there a way to get the index from the QList iterator?

like image 341
sashoalm Avatar asked Mar 12 '14 14:03

sashoalm


2 Answers

You can subtract iterator to beginning of your list from your iterator to get an index, since pointer arithmetic is defined on iterators:

int idx = iter-yourList.begin();

See QList-iterator-reference

like image 132
Ilya Kobelevskiy Avatar answered Oct 21 '22 04:10

Ilya Kobelevskiy


As pointed out by @Frank Osterfeld's comment, you can use this:

const auto index = std::distance(yourList.begin(), currentIteratorOnYourList);

Checkout this article from Fluent{C++} blog.

like image 24
Noam SILVY Avatar answered Oct 21 '22 04:10

Noam SILVY