如何从 std 容器的迭代器为成员元素创建迭代器

How to create iterator for member element from the iterator of std container?

本文关键字:迭代器 成员 元素 创建 std      更新时间:2023-10-16

我只需要为成员元素创建一个迭代器来迭代容器。

例如:

class A { int x; char y; };
std::vector<A> mycoll = {{10,'a'}, {20,'b'}, {30,'c'} };

在这里mycoll.begin()给我 A 类型的迭代器

但是我需要编写迭代器来迭代特定成员(比如 x A.x),并让int_ite成为该整数的迭代器。

然后我需要

返回*(int_ite.begin() ) 10

返回*(++int_ite.begin() ) 20

等等

.end()也会结束迭代。

有没有优雅的方法来创建这样的迭代器?我需要它将其传递给std::lower_bound()

使用 range-v3,您可以创建视图:

std::vector<A> mycoll = {{10,'a'}, {20,'b'}, {30,'c'} };
for (auto e : mycoll | ranges::view::transform(&A::x)) {
    std::cout << e << " "; // 10 20 30
}

对于lower_bound,范围 v3 具有投影:

auto it = ranges::v3::lower_bound(mycoll, value, std::less<>{}, &A::x);
// return iterator of mycoll directly :-)

否则与 std 一起使用,您我使用自定义比较器与std::lower_bound

auto it = std::lower_bound(mycoll.begin(), mycoll.end(),
                           value,
                           [](const A& a, int x){ return a.x < x; });

从 cpp首选项(重载 (2)):

template< class ForwardIt, class T, class Compare >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );

要找到相对于成员x的下界,你可以传递一个比较器,该比较器将该成员作为最后一个参数进行比较。

通常将函子传递给指定如何处理或评估容器元素的算法,而不必编写复杂的迭代器。在标准库中,对编写自己的花哨迭代器的支持相当差,而算法相当强大。