一般来说什么是迭代器? [英] What is an iterator in general?

查看:109
本文介绍了一般来说什么是迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用接受general iterator的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.

(我想将它与 Iterator< T> 中的 Java ,这非常简单,它只是一个类)

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

推荐答案

In C ++ 迭代器概念,不是具体(或抽象)类型,而是任何类型,它遵循某些迭代器,如规则。

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 << '\n';
}

您可以添加一大堆特定检查以确保用户通过了某些操作明智的,但这个问题太宽泛了。

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.

目前概念

这篇关于一般来说什么是迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆