c++ - 如何从 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()
解决方案
使用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; });
推荐阅读
- java - 使用 Observable 更新 TableView 中的行颜色
- gwt - Enum.values() 在 GWT 中不起作用会引发编译错误
- javascript - 将字符串中的十六进制颜色代码替换为彩色 html 标记
- reactjs - 使用 Formik、Yup 和 React 进行异步验证
- python - 如何发布到 AWS IoT 作业
- azure-devops - 用于从外部站点创建分支的深层链接
- android - 如何为 API 级别 16 以上的所有设备发送本地通知?
- java - AssertJ:使用自定义比较器进行流畅的排序测试
- python - 使用 python/opencv/深度学习从图像中删除给定位置的徽标/水印
- postgresql - 使用函数和检查约束或约束触发器的多个表的外键?