user1543042
user1543042

Reputation: 3440

C++ overload [] to access subvector using template

I want to overload the [] vector operator to easily create a temporary subvector.

I thought it would be something like the code shown below. However, when I try to compile I get the error:

error: "operator[]" must be a member function

which [] is a member of vectors.

#include <vector>
#include <algorithm>

using namespace std

template <class T, int a, int b>
T& operator[](int a, int b)
{
    vector<class T> subvector;
    copy ( T.begin() + min(a, b), v1.begin() + max(a, b) + 1, back_inserter(subvector) );

    if (a > b) {reverse(subvector.begin(), subvector.end());};
}

Upvotes: 0

Views: 121

Answers (2)

user123
user123

Reputation: 9071

While some operators like operator+ and operator>> can exist as standalone functions that take some specific number of arguments, operator[] cannot. It must be a member function of a class.

What you're attempting to achieve cannot be done either, because operator[] can only take one argument.

Just use a function:

template<typename T>
std::vector<T> make_sub_vector(std::vector<T> const& v, int begin, int end) {
    assert(begin < end); // Either this, or you swap them 
                         // if this condition is not met.
                         // I'm asserting because I don't know 
                         // what to do when they're equal.
    return std::vector<T>(v.begin() + begin, v.begin() + end);
}

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

According to the C++ Standard

13.5.5 Subscripting

1 operator[] shall be a non-static member function with exactly one parameter. It implements the subscripting

syntax postfix-expression [ expression ]

or

postfix-expression [ braced-init-list ]

Thus, a subscripting expression x[y] is interpreted as x.operator[](y) for a class object x of type T if T::operator[](T1) exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).

Upvotes: 1

Related Questions