Reputation: 11
I'm stumped on my loop. When two lists sizes are equal, I want to compare the contents of it (string and int). I primarily don't understand this part:
The content of all the containers in a BookList is the same - so pick one to walk. If the books are different, you have your answer
Here is my code:
int BookList::compare(const BookList& other) const {
if (!containers_are_consistent() || !other.containers_are_consistent()) {
throw BookList::InvalidInternalStateException(
"Container consistency error in compare");
}
// my implementation starts here
auto begin_this_ = this->books_vector_.begin();
auto begin_other_ = other.books_vector_.begin();
auto end_this_ = this->books_vector_.end();
auto end_other_ = other.books_vector_.end();
if(this->size() == other.size()){
while(begin_this_ != end_this_) {
if(begin_this_ == begin_other_){
++begin_this_;
}
return 0;
if(begin_this_ != begin_other_) {
//what do I do here?
}
}
return 0;
} else if(this->size() < other.size()){
return -1;
} else if(this->size() > other.size()){
return 1;
}
// ends here
}
Upvotes: 0
Views: 911
Reputation: 4046
Firstly, you probably want to compare the contents of the iterators and not the iterators themselves
if (*begin_this_ == *begin_other_) ...
Secondly, you return 0
whenever two iterators compare equal which means you exit the loop.
I suggest you return early only if two elements are NOT equal.
Sadly, you have not described what value is returned if the sizes are equal but the contents are not, so I will assume that the elements are less than comparable
.
Then your while loop will look like
while (begin_this_ != end_this_) {
if (*begin_this_ < *begin_other_)
return -1;
else if (*begin_other_ < *begin_this_)
return 1;
++begin_this_;
++begin_other_;
}
// end of loop which means that all elements are equal
return 0;
Upvotes: 1