假设我有一个这样的结构:
typedef struct
{
foo *fara;
int id;
} fooToIDWrapper_t;
和一个QLinkedList<fooToIDWrapper_t *> FooWrapper;
就这样,
现在我想得到列表fooToIDWrapper_t
所在的迭代器-node 匹配一个特定的 id。
使用 STL 的 std:find_if()
我可以通过这样做来实现这一点(只是示例代码来演示,不检查可编译性):
vector<fooToIDWrapper_t> bar;
auto pred = [ID](const fooToIDWrapper& item) {
return item.id == ID;
};
std::find_if(std::begin(bar), std::end(bar), pred) != std::end(bar);
qt有没有类似的算法?如果不是这样,正如我所假设的那样,我可以通过什么方式在 qt 中实现这一点?
最佳答案
您可以在 find_if
中使用 QLinkedList
!这正是 QLinkedList
提供 cbegin
的原因和 cend
:
find_if(cbegin(bar), cend(bar), [ID](const fooToIDWrapper& item) { return item.id == ID;} ) != cend(bar)
同时考虑:any_of
这似乎更有意义,因为您只是要将生成的迭代器与 cend(bar)
进行比较:
any_of(cbegin(bar), cend(bar), [ID](const fooToIDWrapper& item) { return item.id == ID;})
编辑:
您仍想使用 const
迭代器,因为您不想修改容器。你只需要使用 constBegin
和 constEnd
Qt5之前。所以你可以这样做:
any_of(bar.constBegin(), bar.constEnd(), [ID](const fooToIDWrapper& item) { return item.id == ID;})
如果你觉得需要不断使用the iterator
libraries' accesors对于 Qt4,您将无法使用 const
迭代器:
any_of(begin(bar), end(bar), [ID](const fooToIDWrapper& item) { return item.id == ID;})
关于c++ - qt 是否有来自 STL 的 find_if 之类的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38100760/