【问题标题】:C++ set lower_bound() iteratorC++ 设置 lower_bound() 迭代器
【发布时间】:2016-11-27 06:26:54
【问题描述】:

我想在 C++ 中的 std::set 中找到严格小于给定元素的最大元素。一些问题建议找到 lower_bound 迭代器并将其递减,即

set<int> st;
// Add elements
int x;
// calculate x
auto it = st.lower_bound(x);
if(it != st.begin()) {
    it--;
}

Documentation 不清楚 lower_bound 返回什么类型的迭代器(例如 Forward、Bidirectional),那么我们怎么知道递减这个迭代器是有效的呢?我们也可以估计递减 std::set 迭代器的复杂度吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

    根据documentation of set::lower_bound on cplusplus.com,在“返回值”下:

    成员类型iteratorconst_iterator 是指向元素的bidirectional iterator 类型。

    因此您始终可以递减迭代器(当然,在您的begin 检查之后)。

    递减迭代器的复杂性总是(摊销的)常数。见this answer

    【讨论】:

    • 为了正确起见,您可能需要添加它是摊销常数。
    【解决方案2】:

    std::set::lower_bound的返回类型为std::set::iteratorstd::set::const_iterator,分别是member typesstd::set,都是常量bidirectional iterator

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 2016-03-18
      • 2020-11-08
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2012-03-16
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多