-1

I'm trying to make the iterator work properly, and for the inequality i != a.end().

I get the error

no know conversion from argument 2 from 'const a3::vector<int>::iterator' to 'const a3::vector<int>&

for the friend function. I need the function to check if the iterator is not equal to vector.end() and am unsure how I would do it.

Class

#include <iostream>
using std::cout;
using std::endl;

namespace a3
{
template <typename T>
class vector
{
  public:


  class iterator {
    public:
    int index_;
    vector* a_;

    iterator() : index_(-1), a_(0) {}
    iterator(int index, vector* a) : index_(index), a_(a) {}

    iterator& operator=(const iterator& itr)
    {
      a_ = itr.a_;
      index_ = itr.index_;
      return *this;
    }

    iterator& next() {
      index_++;
      return *this;
    }

    iterator& operator++() {
      return next();
    }




    int& operator*() { return (*a_)[index_]; }
  };

  private:
  T* mem_;
  int sz_;

  public:
  vector(int sz) : sz_(sz), b_(0, this), e_(sz, this)
  {
    mem_ = new T[sz];
  }
  ~vector() { delete[] mem_; }

  const T& operator[](T i) const { return mem_[i]; }
  T& operator[](T i) { return mem_[i]; }

  const int& get_size() const { return sz_; }

  const iterator& begin() { return b_; }
  const iterator& end() { return e_; }

  friend bool operator!=(const iterator& itr1, const vector<T>& vec1)
  {
    return !(itr1.index_ == vec1.end);
  }


  private:
  iterator b_;
  iterator e_;
};
}

Main Function

#include "a3_vector.cpp"


int main(int argc, char** argv)
{
    using namespace a3;
    vector<int> a(10); // allocate an int array of size 10
    for (int i=0; i<10; ++i) a[i] = i*2;

    // a now looks as follows
    //0,2,4,6,8,10,12,14,16,18

    // prints the content of the array
    vector<int>::iterator i;
    for (i = a.begin(); i != a.end(); i.next()) {
        cout << *i << endl;
    }
}
Jason
  • 2,278
  • 2
  • 17
  • 25
student
  • 57
  • 1
  • 5
  • Think a little more about the expression `i != a.end()`, it doesn't compare an iterator to a vector, it compares an iterator with another iterator. And your `operator!=` function doesn't make sense either, it compares an integer with a pointer to a member function. – Some programmer dude Mar 27 '16 at 18:33

1 Answers1

1

This is fundamentally wrong:

friend bool operator!=(const iterator& itr1, const vector<T>& vec1)

Iterator comparisons should compare iterators. What you want are comparison operators that look like this:

friend bool operator!=(const iterator& itr1, const iterator& itr2);
friend bool operator==(const iterator& itr1, const iterator& itr2);

After all, that's what this expression is trying to do:

i != a.end()

You're trying to compare two iterators. The error is just trying to convert a.end() to a const vector<T>&, since that's the match that it found for !=. Simply fix != to take an iterator as the second argument and you'll be fine.

Barry
  • 286,269
  • 29
  • 621
  • 977