首页 > 解决方案 > 如何从 std 容器的迭代器中为成员元素创建迭代器?

问题描述

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

例如:

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()

标签: c++c++11iterator

解决方案


使用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, range-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; });

推荐阅读