Marco A.
Marco A.

Reputation: 43662

How to use begin() and end() in a ranged for loop

Why doesn't this code work?

The error I'm getting is

T *Vector<T>::begin(Vector<T> &)' : expects 1 arguments - 0 provided

code:

#include <iostream>
using namespace std;


template<typename T> class Vector
{
public:

    T* elem;
    int sz;

    Vector()
    {
        elem = new T[2];
        sz = 2;
    }

    template<typename T> T* begin(Vector<T>& x)
    {
        return &x[0];
    }

    template<typename T> T* end(Vector<T>& x)
    {
        return x.begin()+x.size();
    }

    unsigned int size()
    {
        return sz;
    }
};

int main()
{
    Vector<int> ea;

    for(auto& s: ea)
        // do something

    return 0;
}

also I'm not sure of the vector parameter to begin() and end(), why do they need it? They're already member functions so they should have "this" as parameter. I wrote this code but the functions are taken from a book (are they friend??)

Upvotes: 2

Views: 1184

Answers (2)

masoud
masoud

Reputation: 56479

You need Vector::begin() and Vector::end() (without parameters). And the returned values should work as iterators.

 

This could be a similar possible implementation for ranged-based loop:

auto && __range = range_expression;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin)
{
    range_declaration = *__begin;
    // loop_statement
} 

Therefore:

If __range's type is a class type with either or both a begin or an end member function, then begin_expr is __range.begin() and end_expr is __range.end(); 1

 

So, it should be:

T* begin()
{
    return elem;
}

T* end()
{
    return elem + sz;
}

Upvotes: 7

Kostia
Kostia

Reputation: 271

Should be:

template<typename T> T* begin()
{
    return &elem[0];
}

template<typename T> T* end()
{
    return begin() + size;
}

Upvotes: 1

Related Questions