Based on the implementation of Iter, I have difficulties to understand operator!=
and don't understand why it doesn't check _p_vec
?
This is the suggested implementation of operator!=
that ONLY compares the _pos
.
class Iter
{
public:
Iter (const IntVector* p_vec, int pos)
: _pos( pos )
, _p_vec( p_vec )
{ }
// these three methods form the basis of an iterator for use with
// a range-based for loop
bool operator!= (const Iter& other) const
{
return _pos != other._pos;
}
...
...
private:
int _pos;
const IntVector *_p_vec;
};
However, I think the correct way to do this as follows. In other words, we have to compare both _pos
and _p_vec
.
bool Iter::operator!= (const Iter& other) const
{
return _p_vec != other._p_vec || _pos != other._pos;
}
Question> Whose code is correct?
===Update on how std::vector works on comparison of iterator====
std::vector<int> vecOne { 1, 2, 3};
std::vector<int> vecTwo { 4, 5, 6};
auto iterOne = vecOne.begin();
std::advance(iterOne, 1);
auto iterTwo = vecTwo.begin();
std::advance(iterTwo, 1);
if ( iterOne == iterTwo)
std::cout << "iterOne == iterTwo" << std::endl;
else
std::cout << "iterOne != iterTwo" << std::endl;
Output is : iterOne != iterTwo
However,
std::vector<int> foo;
std::vector<int> bar;
if ( foo.begin() == bar.begin() )
std::cout << "foo.begin() == bar.begin()" << std::endl;
else
std::cout << "foo.begin() != bar.begin()" << std::endl;
Output is : foo.begin() == bar.begin()
GCC (version 4.7.1)