简体   繁体   English

将 QList 迭代器转换为索引

[英]Convert QList iterator to index

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).我使用qLowerBoundQList查找一个项目,但是这个函数返回一个迭代器,而我需要一个索引(我会将它传递给另一个需要索引的函数)。 Is there a way to get the index from the QList iterator?有没有办法从QList迭代器中获取索引?

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参见QList-iterator-reference

As pointed out by @Frank Osterfeld's comment , you can use this:正如@Frank Osterfeld 的评论所指出的,你可以使用这个:

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

Checkout this article from Fluent{C++} blog.从 Fluent{C++} 博客查看这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM