【问题标题】:How do I compare two lists using iterators? c++如何使用迭代器比较两个列表? C++
【发布时间】: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_ &lt; *begin_other_,但不一定。请发帖minimal reproducible example
  • 您是否尝试过使用来自&lt;algorithm&gt; 标头的std::equal
  • 如果您使用的是std::vector,您可以简单地将它们与==进行比较:godbolt.org/z/77jTxKMMz

标签: c++ iterator c++17


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 2012-11-05
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多