Hello! I wrote my container class. And now I need to write an iterator class so that my container can interact with the algorithms of the standard library. Wrote a class:

class Iterator { public: Iterator(T *first) { current = first; } T &operator+(int n) { return *(current + n); } T &operator-(int n) { return *(current - n); } T &operator++(int) { return *current++; } T &operator--(int) { return *current--; } T &operator++() { return *++current; } T &operator--() { return *--current; } bool operator==(const Iterator &it) { return current == it.current; } bool operator!=(const Iterator &it) { return current != it.current; } T &operator*() { return *current; } private: T *current; }; 

The code in main:

 Array<int> arr; Array<int> arr2; for (int i(160); i >= 0; i -= 5) { arr.append(i); } for (int i(0); i < 180; i += 5) { arr2.append(i); } sort(arr.begin(), arr.end()); 

As a result, I get a few errors during assembly:

error C2679: binary "-": operator not found, accepting the right operand of the type "Array :: Iterator" (or there is no acceptable transformation)

error C2780: void std :: _ Sort (_RanIt, _RanIt, _Diff, _Pr): requires arguments: 4, available: 3

  • one
    AND? The error message clearly indicates the problem: the iterator subtraction is not implemented. - AnT
  • @AnT can write these implementations in response? I do not quite understand what the difference between binary and unary "-". - Vlad
  • @Vlad c = a - b; - here minus binary, c = -a; - and here is a unary ... - Harry

1 answer 1

I do not know what is wrong with append, but the iterator is implemented incorrectly. Binary operators + and - should return a new iterator, not an object of type T, similarly with the operators ++ and -. Most likely, it should be something like this:

 class Iterator { public: explicit Iterator(T *first): current(first) { } Iterator operator + (int n) const{ return Iterator(current + n); } Iterator operator++(int) { Iterator tmp(current++); return tmp; } Iterator& operator++() { ++current return *this; } Iterator operator - (int n) const{ return Iterator(current - n); } Iterator operator--(int) { Iterator tmp(current--); return tmp; } Iterator& operator--() { --current return *this; } bool operator==(const Iterator &it) const{ return current == it.current; } bool operator!=(const Iterator &it) const{ return !(*this == it); } T &operator*() { return *current; } const T &operator*() const{ return *current; } private: T *current; }; 

PS And do not forget about const.