英文:
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<int>
that is greater than first limit but less than 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;
}
答案1
得分: 2
使用 std::upper_bound
函数:
返回一个迭代器,指向范围
[first, last)
中第一个使得value < element
(或comp(value, element)
)为true
(即严格大于)的元素,如果没有找到这样的元素,则返回last
。
auto it = std::upper_bound(vec.begin(), vec.end(), a);
// 如果找到的值不小于 `b`,则将 `it` 设置为结束迭代器
if (it != vec.end() && not(*it < b)) it = vec.end();
英文:
Use std::upper_bound
:
> Returns an iterator pointing to the first element in the range [first, last)
such that value < 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() && not(*it < b)) it = vec.end();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论