一般来说,什么是迭代器?

2022-01-10 00:00:00 iterator c++

当我尝试使用接受通用迭代器"的 ctor 编写 C++ 类模板时,就会出现这个问题.我不知道这里用general这个词是否合适,但我的意思是它可以像STL容器一样接受迭代器.

This problem comes up when I tried to write a C++ class template with ctor that accept "general iterator". I don't know if it's appropriate to use the word general here, but what I mean is that it can accept iterator just like STL container.

换句话说,我对迭代器感到困惑.似乎所有 STL 容器都有相同的类型迭代器,那么那个类型是什么?它只是指针吗?或者更复杂的东西?但 STL 容器确实接受普通指针.

In other word, I'm confused about iterator. It seems that all STL container has the same type iterator, so what's that type? Is it just pointer? Or something more complicated? But STL container do accept normal pointer.

(我想把它和Java中的Iterator<T>比较一下,很简单,只是一个类)

(I would like to compare it to Iterator<T> in Java, which is quite simple and it's just a class)

推荐答案

在 C++ 中,Iterator 是一个概念,不是具体(或抽象)类型,而是 任何遵守某些 iterator like 规则的类型.

In C++ an Iterator is a concept, not a concrete (or abstract) type, but any type that obeys certain iterator like rules.

例如迭代器通常可以递增++i.可以访问(取消引用)*i 以获取它们当前指向的值.它们本质上是指针的抽象.

For example iterators generally can be incremented ++i. They can be accessed (dereferenced) *i to obtain the value they currently point to. They are essentially abstractions of a pointer.

在标准库的容器中 &算法有不同类型的具有不同属性的迭代器.它们的属性在此处列出:

In the Standard Library's containers & algorithms there are different kinds of iterators with different properties. Their properties are listed here:

https://en.cppreference.com/w/cpp/iterator

所以在用 C++ 编写接受迭代器的算法时,通常只接受 generic 模板参数并在函数中使用适当的迭代器属性.如果用户向您的函数传递了不遵守迭代器规则的内容,编译器会报错:

So when writing algorithms in C++ that accept iterators, generally just accept generic template parameters and use the appropriate iterator properties in the function. The compiler will complain if the user passes something to your function that doesn't obey the iterator rules:

template<typename Iterator>
void my_algorithm(Iterator begin, Iterator end)
{
    for(; begin != end; ++begin)
        std::cout << *begin << '
';
}

你可以添加一大堆特定的检查来确保用户通过了一些合理的东西,但这对于这个问题来说太宽泛了.

You can add a whole bunch of specific checks to make sure the user passed something sensible, but that's too broad for this question.

目前概念,例如Iterator, 只是程序员必须遵循的标准中一组商定的语义属性,一个更全面的解决方案将形式化这样的概念(在代码中)旨在用于下一个标准版本,C++20.

Whilst currently concepts, such as Iterator, are merely a set of agreed upon semantic properties in the Standard that programmers must follow, a more comprehensive solution that will formalize such concepts (in code) is intended for the next version of the Standard, C++20.

相关文章