首页 > 解决方案 > 如何使用迭代器比较两个列表?C++

问题描述

我被我的循环难住了。当两个列表大小相等时,我想比较它的内容(字符串和 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
}

标签: c++iteratorc++17

解决方案


首先,您可能想要比较迭代器的内容而不是迭代器本身

if (*begin_this_ == *begin_other_) ...

其次,0每当两个迭代器比较相等时,您就会返回,这意味着您退出循环。

我建议你只有在两个元素不相等时才早点回来。

可悲的是,如果大小相等但内容不相等,您还没有描述返回什么值,所以我假设元素是less than comparable.

然后你的while循环看起来像

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;

推荐阅读