C++ Question

Discussion in 'Mac Programming' started by nguler, Sep 15, 2005.

  1. nguler macrumors newbie

    Sep 15, 2005
    Is there an easy way to sort two vectors together. I have to columns of data. first column is "run_number", second column is "result".
    I write them into separate vectors. I need to sort the "result" vector, lets say from the lowest to highest value, but without loosing the information which result belongs to which run number..
    Can std::sort make this kind of sorting?
    Any ideas will be appreciated.

  2. ChrisBrightwell macrumors 68020


    Apr 5, 2004
    Huntsville, AL
    You'll probably have to write your own sorting algorithm, but those tend to be pretty painless.

    What you need is some sort of "proxy" lookup table to provide a layer of abstraction between each vector. That's sort of vague, so I hope it makes sense.

    What might be more ideal is to build a vector of RunData objects (which you'll have to build yourself) and sort those. You may still have to write your own sorting algorithm (or, at least, a comparator).

    Once you get that far, your in a much better position to manage the sort, since your coupled data is bound together as a single object.

    You may also consider using an array instead of a vector. Then a simple bubble sort on the array is pretty easy to implement.
    #include <stdio.h>
    #include <conio.h>
    #include "sort.h"
    struct RunData
        int id;
        float result;
    void BubbleSort(RunData DataArray[], int count);
    int main(void)
      StructType  DataArray[1024];
      int  count;
      BubbleSort(DataArray, count);
    void BubbleSort(RunData DataArray[], int count)
      int         i, j;
      RunData temp;
      for(i=0; i<count; i++)
        for(j=0; j<(count-i - 1); j++)
          if(DataArray[j].key > DataArray[j+1].key)
            temp = DataArray[j];
            DataArray[j] = DataArray[j+1];
            DataArray[j+1] = temp;
    If a bubble sort isn't fast enough, there are dozens of other sorting algorithms out there just itching to be used. :)

    FYI -- The code above is off the top of my head. Make sure to check/test it before you just use it.

    Others may disagree, but seperating coupled data like that is typically a bad idea.
  3. cbiffle macrumors member

    Jun 19, 2005
    Tempe, AZ
    Methinks your data is not a vector. Use a map.
  4. superbovine macrumors 68030


    Nov 7, 2003
    beat me to it.
  5. nguler thread starter macrumors newbie

    Sep 15, 2005

Share This Page