Próba użycia pętli for z definiowanym typem – problem przy definicji funkcji begin

0

Witam !
Chciałbym żeby obiekt utworzony z klasy wektor można było użyć w pętli for bez definiowania operatora []

template<typename T>
class Vector {
private:
    T*elem;
    int sz;
public:
    Vector(int s);
    ~Vector() { delete[] elem; }

    T& operator[](int i);
    const T& operator[](int i) const;
    int size() const { return sz; }
};

template<typename T>
Vector<T>::Vector(int s)
{
    elem = new T[s];
    sz = s;
}

template<typename T>
const T& Vector<T>::operator[](int i) const
{
    if (i<0 || size()<=i)
        throw out_of_range{"Vector::operator[]"};
    return elem[i];
}

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

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

void f2(const Vector<string>& vs)
{
    for (auto& s : vs)
        cout << s << '\n';
}

Przy próbie kompilacji otrzymuje :

error: no matching function for call to 'begin(const Vector<std::__cxx11::basic_string<char> >&)'
     for (auto& s : vs)

test.cpp:39:3: note: candidate: template<class T> T* begin(Vector<T>&)
 T*begin(Vector<T>& x)
   ^~~~~
test.cpp:39:3: note:   template argument deduction/substitution failed:
test.cpp:52:20: note:   types 'Vector<T>' and 'const Vector<std::__cxx11::basic_string<char> >' have incompatible cv-qualifiers
     for (auto& s : vs)

Co robię źle ?

2

vs jest const, a Twoje begin/end oczekują non-const.

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

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

Wyrzuciłem const z funkcji f2

void f2(Vector<string>& vs)
{
    for (auto& s : vs)
        cout << s << '\n';
}

teram mam inny error:

test.cpp: In instantiation of 'T* end(Vector<T>&) [with T = std::__cxx11::basic_string<char>]':
test.cpp:52:20:   required from here
test.cpp:47:14: error: 'class Vector<std::__cxx11::basic_string<char> >' has no member named 'begin'
     return x.begin()+x.size();
3

No to już wystarczy przeczytać...

x.begin()

Nie masz takiej funkcji w klasie...

0

Teraz działa.
Wielkie dzięki !

1 użytkowników online, w tym zalogowanych: 0, gości: 1