Qt 获取一个数与离散队列里面的元素按大小排序的位置
可以使用std::lower_bound函数来获取一个数与离散队列里面的元素按大小排序的位置。
假设离散队列为std::vector<int> nums,要查找的数为int target,首先需要确保nums是按照从小到大的顺序排序的。然后,使用std::lower_bound函数可以找到第一个不小于target的元素的位置,即为所求。
以下是一个示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {3, 5, 7, 9, 11};
int target = 8;
// 确保 nums 是按从小到大排序的
std::sort(nums.begin(), nums.end());
// 使用 std::lower_bound 查找位置
auto it = std::lower_bound(nums.begin(), nums.end(), target);
int position = it - nums.begin();
std::cout << "Position: " << position << std::endl;
return 0;
}
在上面的示例中,离散队列nums为{3, 5, 7, 9, 11},要查找的数target为8。首先使用std::sort函数对nums进行排序,然后使用std::lower_bound函数查找target的位置,最后输出结果为Position: 3,表示target在nums中的位置为索引3
原文地址: https://www.cveoy.top/t/topic/iZgt 著作权归作者所有。请勿转载和采集!