M
matthurne
I am working through exercise 8-2 in Accelerated C++...I am
implementing the function equal(b, e, b2) where b is an iterator for
the first element in a container, e is an iterator pointing to one
past the last element in that same container, and b2 is an iterator
for the first element in the second container. Here's what I have:
template <class T>
bool equal(T begin, T end, T begin2) {
while (begin != end) {
if (*begin != *begin2) {
return false;
}
++begin;
++begin2;
}
return true;
}
This seems to work fine when the two containers are of the same size,
which is a precondition of the function. However, I noticed that the
equal method in the standard library returns false if two containers
of differing sizes are given to it. This makes complete sense, and I
want my function to behave that way as well. Right now it does
not...I keep getting back true if the containers have differing sizes.
So my questions then are: what happens when you increment an iterator
once it refers to one past the last element in the container? Does it
actually change or does it say put? If it changes, what happens when
you dereference an iterator that does not refer to a valid element?
And of course the big question: how can I write my function to behave
correctly and return false when two containers have different numbers
of elements?
Thanks!
implementing the function equal(b, e, b2) where b is an iterator for
the first element in a container, e is an iterator pointing to one
past the last element in that same container, and b2 is an iterator
for the first element in the second container. Here's what I have:
template <class T>
bool equal(T begin, T end, T begin2) {
while (begin != end) {
if (*begin != *begin2) {
return false;
}
++begin;
++begin2;
}
return true;
}
This seems to work fine when the two containers are of the same size,
which is a precondition of the function. However, I noticed that the
equal method in the standard library returns false if two containers
of differing sizes are given to it. This makes complete sense, and I
want my function to behave that way as well. Right now it does
not...I keep getting back true if the containers have differing sizes.
So my questions then are: what happens when you increment an iterator
once it refers to one past the last element in the container? Does it
actually change or does it say put? If it changes, what happens when
you dereference an iterator that does not refer to a valid element?
And of course the big question: how can I write my function to behave
correctly and return false when two containers have different numbers
of elements?
Thanks!