迭代器如何映射/知道它们的当前位置或元素
How do iterators map/know their current position or element
考虑以下代码示例:
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <functional>
int main()
{
std::vector<int> v(10, 2);
std::partial_sum(v.cbegin(), v.cend(), v.begin());
std::cout << "Among the numbers: ";
std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << 'n';
if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })) {
std::cout << "All numbers are evenn";
}
if (std::none_of(v.cbegin(), v.cend(), std::bind(std::modulus<int>(),
std::placeholders::_1, 2))) {
std::cout << "None of them are oddn";
}
struct DivisibleBy
{
const int d;
DivisibleBy(int n) : d(n) {}
bool operator()(int n) const { return n % d == 0; }
};
if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) {
std::cout << "At least one number is divisible by 7n";
}
}
如果我们看一下这部分代码:
if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })) {
std::cout << "All numbers are evenn";
}
很容易理解。它遍历这些向量元素,并找出i%2==0
,它们是否能被2完全整除,从而找出它们是否为偶。
对应的for循环可以是这样的:
for(int i = 0; i<v.size();++i){
if(v[i] % 2 == 0) areEven = true; //just for readablity
else areEven = false;
}
在这个for循环的例子中,很明显我们正在处理的元素是i
,因为我们实际上访问的是v[i]
。但是为什么在相同代码的迭代器版本中,它映射i
或者知道我们正在访问的当前元素是什么?
[](int i){ return i % 2 == 0; })
如何确保/知道i是迭代器所指向的当前元素
如果不使用任何v.currently_i_am_at_this_posiition()
,我无法弄清楚迭代是如何完成的。我知道迭代器是什么,但我很难掌握它们。谢谢:)
迭代器以指针为模型,实际上就是这样。它们如何在内部工作并不重要,但是可能的实现实际上是在内部有一个指向当前元素的指针。
通过使用迭代器对象
完成迭代迭代器是任何对象,它指向的元素位于元素(如数组或容器)具有迭代的能力使用一组操作符(带at)遍历该范围内的元素最小自增(++)和解引用(*)操作符。
迭代器最明显的形式是指针:指针可以指向数组中的元素,并且可以使用自增操作遍历它们操作符(+ +).
,并在元素集合中推进它。代码中的std::all_of
函数大致相当于以下代码
template< class InputIt, class UnaryPredicate >
bool c_all_of(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first) {
if (!p(*first)) {
return false; // Found an odd element!
}
}
return true; // All elements are even
}
迭代器自增时跟踪当前指向的元素,解引用时返回当前指向的元素的值。
为了便于教学和清楚起见,您也可以这样考虑操作(不要在家里尝试)
bool c_all_of(int* firstElement, size_t numberOfElements, std::function<bool(int)> evenTest)
{
for (size_t i = 0; i < numberOfElements; ++i)
if (!evenTest(*(firstElement + i)))
return false;
return true;
}
请注意,迭代器是一个强大的抽象,因为它们允许在不同的容器(例如std::map
)中访问一致的元素。
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 求最大元素位置的分治算法
- 如何将元素添加到向量的字符串位置
- 这个返回元素位置的基于循环的函数有什么问题?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 数组中所有元素的最新最小元素的第五个位置
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 如何从几乎排序的链表中分离放错位置的元素?
- 如何获得相同数量的第一个和第二个元素以及它们在c++中各自的位置
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 这是查找向量中元素位置的合法方法吗?
- 用于在字符串(C )向量中找到元素位置的函数中的错误
- 如何比较和存储 2 个向量的数据元素位置
- 获取与特定模式距离最小的矢量的元素位置
- 最大 N 个等元素位置的 C++ 向量
- OpenCV 从矩阵中获取条件基最大元素位置
- 有没有一种方法可以从传递给排序的lambda中获取元素位置
- 标准::多集,跟踪插入的元素位置
- 在C++中指定数组声明中的元素位置
- 获取std::vector中的元素位置