2

I am trying to sort two sets of data, that are either in a 2d array or parallel arrays, either way it makes no difference but I cant seem to figure it out. Here are the two arrays:

/////way one///

int id[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numDetected[10] = {40, 21, 2, 19, 45, 32,43, 90, 100, 8};

or

int 2dArray[2][10];

it makes no difference, but I cant seem to figure this out.

I want to order the arrays into a new array, (whether it is a 2d array or parrellel arrays) by the numDetected amount. So the largest numDetected is at element zero and the smallest at the end. But while doing that, I want to keep the id associated with that in the same element as the numDetected. So if numDetected[2] is the largest, I want numDetected[2] and id[2] to be the first elements in the new arrays.

Can anyone help me out?

1
  • Wouldn't it be easier to have a struct item { int id; int numDetected; } and a container of those structs? And preferably operator< for that struct? That would make it a lot easier. Commented Feb 28, 2013 at 23:10

1 Answer 1

1
struct values
{
    int id;
    int detected;
} data[10] = ...;

// intentionally reversed to cause sort in descending order
bool operator<(const values& left, const values& right) { return left.detected > right.deteted; }

values *begin = data, *end = (&data)[1];
std::sort(begin, end);
Sign up to request clarification or add additional context in comments.

3 Comments

It's cool to see that my idea was the one that you came up with. :)
I don't understand what you're doing with (&data)[1]. What is that?
@nbubis: No, it's not. It uses pointer arithmetic on a pointer-to-array-of-10-ints. Therefore when everything gets scaled by the type size, the type is "array of 10 ints" and it moves right to the end of the whole array. Don't try that with a pointer though, only with an actual array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.