获得大于等于x的第一个数

img

有没有佬佬帮我看看我的做法哪里错了啊?谢谢!不知道哪里出错了,谢谢!

找出大于x的最小值!!!你要遍历数组,将第一次大于x的数保存,之后遇到大于X的数要与保存的数进行比较,将较小的保存。
遍历完成后输出

【以下回答由 GPT 生成】

问题描述: 你希望编写一个C++程序,用于给定一个大小为n的数组a和m次询问的情况下,找到数组a中大于指定数x的最小值。你已经尝试使用集合set来实现,但遇到了一些错误。你希望得到对你的代码进行检查和指导的帮助。

示例输入:

5 3
6 3 8 5 9
7
3
10

示例输出:

8
5
-1

代码:

#include <iostream>
#include <set>
#include <algorithm>

int main() {
    int n, m;
    std::cin >> n >> m;

    std::set<int> a;
    for (int i = 0; i < n; i++) {
        int num;
        std::cin >> num;
        a.insert(num);
    }

    for (int i = 0; i < m; i++) {
        int x;
        std::cin >> x;

        // Find the smallest number in the set greater than x
        auto it = std::upper_bound(a.begin(), a.end(), x);

        if (it != a.end()) {
            std::cout << *it << std::endl;
        } else {
            std::cout << -1 << std::endl;
        }
    }

    return 0;
}

你遇到的问题是什么?



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^