【发布时间】:2021-12-01 18:09:13
【问题描述】:
我被我的循环难住了。当两个列表大小相等时,我想比较它的内容(字符串和 int)。我主要不明白这部分:
BookList 中所有容器的内容都是相同的 - 所以选择一个走。如果书籍不同,你有你的答案
这是我的代码:
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
}
【问题讨论】:
-
您需要在“遍历”列表时移动两个迭代器,并一直这样做直到结束。如果你走到了尽头,或者没有走到尽头,你就会知道答案
-
问题是,什么是 BookList。迭代器具有不寻常的比较语义或比较错误
-
BookList是什么?目前尚不清楚如何从您发布的代码中比较列表中的两个元素。通常是*begin_this_ < *begin_other_,但不一定。请发帖minimal reproducible example -
您是否尝试过使用来自
<algorithm>标头的std::equal? -
如果您使用的是
std::vector,您可以简单地将它们与==进行比较:godbolt.org/z/77jTxKMMz