【问题标题】:c++, speeding up a program that compares two lines of arrays and returns the ones that re in the first, but not the secondc ++,加速比较两行数组并返回第一行但不返回第二行的程序
【发布时间】:2021-03-23 16:48:41
【问题描述】:

所以我有 2 行数组。第一行是M,第二行是N。 在第一行,用户输入 2 个数字,第一个是 M 的长度,第二个是 N 的长度。 在第二行,用户输入 M,在第三行 - N。我只想显示 N 的哪些元素不包含在 m 中,而是按 升序 顺序显示。 这是一个例子:

7 5

3.12 7.96 3.51 4.77 10.12 1.11 9.80

10.12 3.51 3.12 9.80 4.77

输出:

1.11 7.96

这是我对该程序的尝试:

#include <stdio.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;

int ifexists(double z[], int u, int v)
{
    int i;
    if (u == 0)
        return 0;
    for (i = 0; i <= u; i++)
        if (z[i] == v)
            return (1);
    return (0);
}
void main()
{
    double bills[100], paid[100], result[100];
    int m, n;
    int i, j, k;
    cin >> m >> n;
    if (n > m) {
        cout << "Wrong input.";
        exit(3);
    }
    for (int i = 0; i < m; i++) {
        cin >> bills[i];
    }
    for (int i = 0; i < n; i++) {
        cin >> paid[i];
    }
    for (i = 0; i < n; i++)
        k = 0;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            if (bills[i] == paid[j]) {
                break;
            }
        }
        if (j == n) {
            if (!ifexists(result, k, bills[i])) {
                result[k] = bills[i];
                k++;
            }
        }
    }
    for (i = 0; i < k; i++)
        cout << result[i] << " ";
}

我得到的输出几乎是正确的 - 7.96 1.11。基本上是相反的顺序。我怎样才能翻转这个?另外,我的报告可能太慢了。有没有办法提高速度?

【问题讨论】:

标签: c++ arrays sorting time


【解决方案1】:

你可以使用std::set_difference:

std::sort(bills, bills + m);
std::sort(paid, paid + n);
auto end = std::set_difference(bills, bills + m, paid, paid + n, result);
for (auto it = result; it != end; ++it) {
    std::cout << *it << " ";
}

【讨论】:

    猜你喜欢
    • 2016-01-25
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2020-10-14
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多