找到第一个大于第一个限制但小于第二个限制的元素的索引,高效地。

huangapple go评论68阅读模式
英文:

find the index of very first element that is greater than first limit but less than second limit efficiently

问题

I need to find the index of the very first element in a sorted std::vector<int> that is greater than the first limit but less than the second limit efficiently.

#include <iostream>
#include <vector>

int main() {
    const int a = 2, b = 4; // a is always less than b
    const std::vector<int> vec {1, 2, 3, 4, 5};

    // an efficient algo that will return an iterator to the 
    // first element in vec that is greater than a but less than b
    int ans = -1;
    for (const auto x : vec) {
        if (x > a && x < b) {
            ans = x;

            break;
        }
    }

    std::cout << ans << std::endl;
}
英文:

I need to find the index of very first element in a sorted std::vector&lt;int&gt; that is greater than first limit but less than second limit efficiently.

#include &lt;iostream&gt;
#include &lt;vector&gt;

int main() {
    const int a = 2, b = 4; // a is always less than b
    const std::vector&lt;int&gt; vec {1, 2, 3, 4, 5};

    // an efficient algo that will return an iterator to the 
    // first element in vec that is greater than a but less than b
    int ans = -1;
    for (const auto x : vec) {
        if (x &gt; a &amp;&amp; x &lt; b) {
            ans = x;

            break;
        }
    }

    std::cout &lt;&lt; ans &lt;&lt; std::endl;
}

答案1

得分: 2

使用 std::upper_bound 函数:

返回一个迭代器,指向范围 [first, last) 中第一个使得 value &lt; element(或 comp(value, element))为 true(即严格大于)的元素,如果没有找到这样的元素,则返回 last

auto it = std::upper_bound(vec.begin(), vec.end(), a);
// 如果找到的值不小于 `b`,则将 `it` 设置为结束迭代器
if (it != vec.end() && not(*it &lt; b)) it = vec.end();
英文:

Use std::upper_bound:
> Returns an iterator pointing to the first element in the range [first, last) such that value &lt; element (or comp(value, element)) is true (i.e. strictly greater), or last if no such element is found.

auto it = std::upper_bound(vec.begin(), vec.end(), a);
// set `it` to the end iterator if the found value is not less than `b`
if(it != vec.end() &amp;&amp; not(*it &lt; b)) it = vec.end();

huangapple
  • 本文由 发表于 2023年7月6日 18:11:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定