如何从 std 容器的迭代器为成员元素创建迭代器
How to create iterator for member element from the iterator of std container?
我只需要为成员元素创建一个迭代器来迭代容器。
例如:
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
的下界,你可以传递一个比较器,该比较器将该成员作为最后一个参数进行比较。
通常将函子传递给指定如何处理或评估容器元素的算法,而不必编写复杂的迭代器。在标准库中,对编写自己的花哨迭代器的支持相当差,而算法相当强大。
相关文章:
- "迭代器"和"const_iterator"不是 STL 容器的必需成员?
- 如何将迭代器调用转发给类的私有成员?
- 成员函数中的迭代器出现问题
- 如何在C++中仅获取容器内类成员的迭代器
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 为什么向量的.at()成员函数返回引用而不是迭代器
- 将列表迭代器存储为成员
- 使用迭代器成员函数是否仅适用于某些向量类型"empty()"?
- C++ 向量::使用类对象迭代器擦除不擦除向量成员
- 树不维护递归迭代器成员
- 如何将迭代器变量声明为私有成员变量
- 我如何从循环内部使用迭代器的函数内部的getter中检索特定的成员
- C :我可以将成员变量的迭代器带入班级之一
- 如何使用C STD :: SET中的迭代器访问成员功能
- C++:将成员容器的迭代器接口转发到类接口
- 如何从 std 容器的迭代器为成员元素创建迭代器
- 通过迭代器为映射的成员赋值
- 如果我创建一个修改值的迭代器,静态成员"reference"应该是什么类型?
- C++迭代器作为类方法中使用的类成员
- 类成员向量上的迭代器未正确取消引用