sorting question

I have two vectors a string vector and a double vector of the same length namely, vector1={dog, cat, giraffe, rabbit, snake} and vector2={2.3, 19, 5.67, 4, 1.004}. I want to know lets say you want to sort both vector2 so that it now reads from the highest number to the lowest, but you want it so that vector1 also gets sorted in the same way. Such that 19 corresponds to cat and gets moved to first and so cat also gets moved to first. If done correctly after being sorted the vectors would read as vector1={cat, giraffe, rabbit, dog, snake} and vector2={19, 5.67, 4, 2.3, 1.004}. I know one can use std::sort but I'm not sure how to use it to sort two different vectors at the same time in this fashion.
I would guess you would want to use maps: http://www.cplusplus.com/reference/map/map/
Also check the sorting functions in <algorithm>: http://www.cplusplus.com/reference/algorithm/

Aceix.
Here's one way you might accomplish that:

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
39
40
41
#include <vector>
#include <string>
#include <numeric>
#include <algorithm>
#include <iostream>
#include <iomanip>

template <typename T, typename U, typename V>
void print_parallel(const T& a, const U& b, const V& idx)
{
    for (unsigned i = 0; i < a.size(); ++i)
    {
        std::cout << std::left << std::setw(10) << a[idx[i]];
        std::cout << std::right << std::setw(10) << b[idx[i]] << '\n';
    }
}

int main()
{
    std::vector<std::string>  aminals = { "dog", "cat", "giraffe", "rabbit", "snake" };
    std::vector<double> values = { 2.3, 19.0, 5.67, 4, 1.004 };

    auto by_aminal = [&](unsigned i, unsigned j) { return aminals[i] < aminals[j]; };
    auto by_value = [&](unsigned i, unsigned j) { return values[i] < values[j]; };

    std::vector<unsigned> indices(aminals.size());
    std::iota(indices.begin(), indices.end(), 0);

    std::cout << "Before sort by value:\n";
    print_parallel(aminals, values, indices);

    std::sort(indices.begin(), indices.end(), by_value);

    std::cout << "\nAfter sort by value:\n";
    print_parallel(aminals, values, indices);

    std::sort(indices.begin(), indices.end(), by_aminal);

    std::cout << "\nAfter sort by aminal:\n";
    print_parallel(aminals, values, indices);
}


http://ideone.com/NqBqsS
Last edited on
I know I will invite a lot of flak, but I can't resist pointing you to a recent post of mine. You seem to want the exact same thing.

http://www.cplusplus.com/forum/lounge/130289/#msg703496
Caveat: Bubble sort is inefficient.
Last edited on
Topic archived. No new replies allowed.