为什么我不能使用list iterator逻辑比较运算符? [英] why can't i use list iterator logical comparisons operator?

查看:199
本文介绍了为什么我不能使用list iterator逻辑比较运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是非常基本的,但我在这里找不到类似的问题。我试图使用列表从不同的方向迭代相同的排序STL列表。我知道我可以将迭代器与 list.begin() list.end()进行比较,那么为什么呢这不行吗?

It's very basic, but I could not find a similar question here. I am trying to iterate the same sorted STL list from different directions using list. I know I can compare an iterator to the list.begin() and list.end(), so why doesn't this work?

list<family>::iterator itLargeFamily = 
                  families.begin(); //starts from the biggest families
list<family>::iterator itSmallFamily = 
                  families.end(); //starts from the smallest families

for (; itSmallFamily > itLargeFamily; --itSmallFamily, ++itLargeFamily) {
    // stuff...
}

错误当然是


没有运算符>匹配这些操作数

no operator > matches these operands

100%几率我遗漏了一些基本的东西。

100% chance I'm missing something basic.

推荐答案

从sftrabbit的注释和答案中可以看出,关系运算符仅定义为随机访问迭代器, std :: list 只有双向迭代器。因此,有几种解决方案可以解决您的问题:

From the comments and the answer of sftrabbit you can see that relational operators are only defined for random access iterators, and std::list has only bidirectional iterators. So there are several solutions for your problem:


  1. 使用 std :: vector 的std ::阵列。它们提供随机访问迭代器,对于较小的尺寸具有更好的性能,并且取决于您如何填充/使用它们以获得更大的尺寸,并且它们具有更好的内存占用。这是首选的解决方案,我称之为默认解决方案。仅在存在非常好的,可测量的原因时才使用其他容器(例如,分析器告诉您使用该容器是性能瓶颈)。

  2. 因为您知道的大小列表,您可以使用计数器进行迭代:

  1. Use std::vector or std::array. They provide random access iterators, have better performance for smaller sizes, and depending of how you fill/use them for larger sizes as well, and they have better memory footprint. This is the preferred solution, I'd call it the "default" solution. Use other containers only if there is a very good, measurable reason (e.g. a profiler tells you that using that container is a performance bottleneck).
  2. Since you know the size of the list, you can use a counter for your iterations:

for (size_t i = 0, count = families.size()/2; 
     i < count; 
     ++i, --itSmallFamily, ++itLargeFamily)
{ /* do stuff */ }


  • 由于列表已排序,您可以比较迭代器指向的元素而不是迭代器本身。

  • Since your list is sorted, you can compare the elements the iterators point to instead of the iterators themselves.

    这篇关于为什么我不能使用list iterator逻辑比较运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆