【问题标题】:Is there a way to compare multiset iterators?有没有办法比较多集迭代器?
【发布时间】:2021-09-13 22:04:55
【问题描述】:

我想知道是否有办法比较多集迭代器?我有兴趣做以下事情:

    std::multiset<int> mt{1,1,1,1,3,4,5};
    auto it1 = mt.find(3);
    auto it2 = mt.find(1);
    cout << (it1 < it2) << endl; // this should print "0"
    it1 = mt.find(equal_range);
    auto p = mt.equal_range(1);
    cout << (p.first < p.second) << endl; // this should print "1"

但是我无法在多集迭代器上使用比较运算符。

如果集合中的值是唯一的,我可以只比较迭代器的取消引用版本,但我专门使用多重集,因为值可能不是唯一的,如果 2 个迭代器指向相同值的不同实例,我需要一种方法来根据它们在底层树中的相对位置来比较它们。

【问题讨论】:

  • 读起来好像要比较std::distance(mt.begin(), it)

标签: c++ multiset


【解决方案1】:

有没有办法比较多集迭代器?

没有有序的比较。双向迭代器通常不需要/保证不可比。

您面临的问题本质上与找出链表中元素的顺序相同。线性复杂度算法是可能的:

 std::distance(std::begin(mt), it1) < std::distance(std::begin(mt), it2)

平等比较是微不足道的。

【讨论】:

    猜你喜欢
    • 2015-08-12
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2016-09-23
    相关资源
    最近更新 更多