As an exercise, I'm trying to write a custom iterator to be used by std::sort
. From its doc, I read:
[My iterator] must meet the requirements of ValueSwappable and
RandomAccessIterator.
Without fully implementing those1, I've come to this MCVE:
#include <iostream>
#include <algorithm>
struct mcve_random_access_iterator
{
using size_type = std::size_t;
using value_type = int;
size_type _index;
value_type* _values;
mcve_random_access_iterator(value_type* values) : _index(0), _values(values) {}
mcve_random_access_iterator& operator-(const mcve_random_access_iterator& rhs) { _index-=rhs._index ; return *this; }
value_type& operator*() { return _values[_index]; }
friend bool operator==(mcve_random_access_iterator& lhs, mcve_random_access_iterator& rhs) { return lhs._index == rhs._index; }
friend bool operator!=(mcve_random_access_iterator& lhs, mcve_random_access_iterator& rhs) { return !(lhs == rhs); }
};
void swap(mcve_random_access_iterator& lhs, mcve_random_access_iterator& rhs)
{
std::swap(*lhs, *rhs);
}
struct mcve_container
{
int _values[3];
mcve_container() : _values{2, 3, 1} {}
mcve_random_access_iterator begin() { return {_values}; }
mcve_random_access_iterator end() { auto b = begin(); b._index = sizeof(_values)/sizeof(_values[0]); return b; }
};
int main()
{
mcve_container data;
std::sort(data.begin(), data.end());
for (auto n : data._values)
std::cout << n << ", ";
std::cout << "\n";
}
Compiling with g++ 7.2.0, I get the following error:
/usr/local/include/c++/7.2.0/bits/stl_algo.h:1969:14: error: no matching function for call to '__lg(mcve_random_access_iterator&)' std::__lg(__last - __first) * 2,
Why do I get this error and how to address it?
1) I've stripped all requirements of RandomAccessIterator from mcve_random_access_iterator
which still reproduce the error.