Arranging output by comparing with inputs

Hi guys, I am learning C++.

I have two datasets like below:

set1: 57.5276, 55.3756, 24.2798, 54.5989

and

set2: 55.1118, 55.004, 24.824, 57.1398

Now I want to arrange the second set such that it matches the closest distance (eg. set1[0]-set2[3] == Min) to the first set (I mean 57.1398, 55.1118, 24.824, 55.004 this order).
How Can I do that in C++.

Last edited on
Maybe you can just sort the lists and match up the values pairwise.
Storing the original indices allows you to keep the original order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <vector>
#include <algorithm>

struct Value {
    size_t ind;
    double val;
};

int main() {
    double a[] {57.5276, 55.3756, 24.2798, 54.5989};
    double b[] {55.1118, 55.004,  24.824,  57.1398};
    size_t size = sizeof a/sizeof a[0];

    // Store a's values along with the original indices.
    std::vector<Value> v;
    v.reserve(size);
    for (size_t i = 0; i < size; i++)
        v.push_back({i, a[i]});

    // Sort v by the values.
    std::sort(v.begin(), v.end(),
        [](const Value& x, const Value& y){return x.val < y.val;});

    // Sort b.
    std::sort(&b[0], &b[size]);

    // Match them up pairwise but store b's values at a's values' original indices.
    auto c = new double[size];
    for (size_t i = 0; i < size; i++)
        c[v[i].ind] = b[i];

    // Print.
    for (size_t i = 0; i < size; i++)
        std::cout << c[i] << '\n';

    delete [] c;
}

Thanks...This works nicely
Topic archived. No new replies allowed.