c++ - 如何使用迭代器比较两个列表?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
}
解决方案
首先,您可能想要比较迭代器的内容而不是迭代器本身
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;
推荐阅读
- java - 表达式JAVA的非法开始
- php - 使用功能来选择、更新、删除和插入数据库安全吗?
- r - 为什么在执行 1D-CNN 时 R 会话中止?
- ios - 原生模块不暴露给 Javascript 的条件
- python - 将具有多个语句的 Python 函数转换为 lambdas
- django - django-rest-swagger UI 没有 POST 请求正文的表单(基于函数的视图)
- c# - 实体框架核心创建额外的表列
- java - 从 Android Studio 导入项目时出现 Intellij Idea 错误
- python-3.x - Tkinter 文本小部件插入图像
- linux - 如果前一个进程包含字符串,则在后台运行进程的 Shell 脚本解析其输出并启动服务