简体   繁体   English

从指针返回迭代器

[英]Returning an iterator from a pointer

I have two simple container: one that stores a pointer and another one that stores a flat_set of pointers.我有两个简单的容器:一个存储指针,另一个存储指针的 flat_set。 In order to be able to use for(auto ...) on both of them (or stl algorithms), I would like to add begin/end to them.为了能够在它们(或 stl 算法)上使用 for(auto ...),我想为它们添加开始/结束。 For the one with the flat_set, I just have to return the iterators of the flat_set but how can I do the same for the container that just holds a pointer?对于带有 flat_set 的那个,我只需要返回 flat_set 的迭代器,但是我怎么能对只保存一个指针的容器做同样的事情呢?

I would like to avoid having to create a complete iterator class just for that... Basically, I would like to do something like that:我想避免为此创建一个完整的迭代器类......基本上,我想做这样的事情:

class Container
{
    ...
    Iterator begin() { return the_pointer; }
    Iterator end() { return the_pointer+1; }
    private:
    int* the_pointer;
}

But I don't know which signature Iterator must have.但我不知道 Iterator 必须有哪个签名。

Thanks !谢谢 !

Pointers to object types are valid iterator types, so you can just return a pointer.指向对象类型的指针是有效的迭代器类型,因此您可以只返回一个指针。 In fact std::array<T,N> has T* as its iterator type.事实上std::array<T,N>T*作为它的迭代器类型。

If your container holds sequence of pointers (they stored in memory like normal array), then you can simply return pointer from your class如果您的容器包含指针序列(它们像普通数组一样存储在内存中),那么您可以简单地从您的类中返回指针

int * begin();
int * end();

It is because for ( ... : ... ) syntax is expanded to something like:这是因为 for ( ... : ... ) 语法被扩展为类似:

for ( auto begin = container.begin(), end = container.end();
      begin != end; ++begin )
 // ...

C pointers are legal iterators. C 指针是合法的迭代器。 Here you can check an useful guide on them with a section on how to implement iterators from pointers. 在这里,您可以查看有关它们的有用指南,其中包含有关如何从指针实现迭代器的部分。 Basically you need to implement begin() and end() returning first and last valid pointers.基本上你需要实现begin()end()返回第一个最后一个有效指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM