迭代器如何映射/知道它们的当前位置或元素

How do iterators map/know their current position or element

本文关键字:元素 位置 何映射 映射 迭代器      更新时间:2023-10-16

考虑以下代码示例:

#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)中访问一致的元素。