Search code examples
c++stl-algorithm

begin() and end() for STL algorithms


I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().

template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.
note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?

std::copy(begin(), end(), someOutputIterator);

Solution

  • Is this caused by incorrect begin() and end() implementations?

    Yes, you need const versions of the functions. For example:

    template <size_t size>
    const double * MyContainerClass<size>::begin() const {
        return std::begin(mContainer);
    }