C ++ foreach loop with pointers instead of links

I have a class Containerwith begin () and end () functions for use with C ++ 11 foreach loops:

class Element
{
    //content doesn't matter
};

class Container
{
    Element* elements;
    int size;

    /* constructor, destructor, operators, methods, etc.. */

    Element* begin() { return elements; };
    Element* end()   { return elements + size; };
};

Now this is a valid C ++ 11 foreach loop:

Container container;
for (Element& e : container)
{
    //do something
}

But now consider this foreach loop:

Container container;
for (Element* e : container)
{
    //do something
}

Is it possible to have a foreach loop with Element*instead of Element&as follows?
It would also be a great advantage in not clicking for (Element e : container), which will copy an item every time.

In this case, begin()they end()should have been returned Element**, as far as I know.

But it is sizeof(Element)not guaranteed sizeof(Element*), and in most cases they do not match. Increment the increment of the pointer to the size of the base type, which is sizeof(Element)for increasing Element*and sizeof(Element*)for increasing Element**.

, operator++() , . , ?

+4
2

LRiO, , , - . , , , ( ).

, :

class Container
{
    // ...

    struct iterator {
        Element* e;

        // this is the important one
        Element* operator*() { return e; }

        // the rest are just boilerplate
        iterator& operator++() { ++e; return *this; }
        iterator operator++(int) {
            iterator tmp{e};
            ++*this;
            return tmp;
        }

        bool operator==(iterator rhs) const { return e == rhs.e; }
        bool operator!=(iterator rhs) const { return e != rhs.e; }
    };

    iterator begin() { return {elements}; };
    iterator end()   { return {elements + size}; };
};

std::iterator, typedefs, boost::iterator_facade. , , .

+5

, , Element*Element , Element&Element . , , , .

, , , & hellip; , .

.

+2

All Articles