Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从std容器的迭代器为成员元素创建迭代器?_C++_C++11_Iterator - Fatal编程技术网

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

C++ 如何从std容器的迭代器为成员元素创建迭代器?,c++,c++11,iterator,C++,C++11,Iterator,我只需要为成员元素创建一个迭代器来遍历容器 例如: class A { int x; char y; }; std::vector<A> mycoll = {{10,'a'}, {20,'b'}, {30,'c'} }; 这里mycall.begin将为我提供类型为A的迭代器 但是我需要编写迭代器来迭代特定的成员,比如xa.x,并让int_ite作为该整数的迭代器 那么我需要 *int_ite.开始返回10 *++int_ite.开始返回20 等等 另外,end将给出迭代的结束

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

例如:

class A { int x; char y; };

std::vector<A> mycoll = {{10,'a'}, {20,'b'}, {30,'c'} };

这里mycall.begin将为我提供类型为A的迭代器

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

那么我需要

*int_ite.开始返回10

*++int_ite.开始返回20

等等

另外,end将给出迭代的结束

有什么优雅的方法可以创建这样的迭代器吗? 我要求它将其传递给std::lower_bound

,您可以创建视图:

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
}
对于std,您可以使用自定义比较器和std::lower_bound

从过载2:

要找到与成员x相关的下限,可以传递一个比较器,将该成员作为最后一个参数进行比较


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

您不能使用int_ite.begin->x?您在创建迭代器时发现了什么问题?你试过写迭代器了吗?当然可以实现像迭代器那样只返回字段x的东西,但是对于std::lower_bound你也不需要它,一个自定义比较器来完成这项工作。旁注:如果你发现自己真的需要这样做,关于如何开始制作容器及其迭代器。感谢您的代码。问题的解决办法并不那么明显。
auto it = ranges::v3::lower_bound(mycoll, value, std::less<>{}, &A::x);
// return iterator of mycoll directly :-)
auto it = std::lower_bound(mycoll.begin(), mycoll.end(),
                           value,
                           [](const A& a, int x){ return a.x < x; });
template< class ForwardIt, class T, class Compare >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );