用于 STL 算法的 begin() 和 end()

begin() and end() for STL algorithms

我有一个 class,它的数据容器由数组支持,我有以下 begin()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);
}

在其他成员函数中,我试图将begin()end() 用于STL 算法,例如std::transformstd::copy。当const对象作为参数传递给这些成员函数时,我遇到错误:

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

这是由于 begin()end() 实施不正确造成的吗?

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

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

是的,您需要 const 个版本的函数。例如:

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

这里的重点是 'const':您需要提供 begin()end() 函数的其他 const 版本,即 return const double*.

如果您使用的是 C++ 11,您可能还需要提供 cbegin()cend()