Sorting vector inside structure

Hi everybody,

What I did is, I have 2 one dimensional vector which are inside structure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int numberofactivities;
struct PopL{
		vector<double> RK; //For Random Key
};
//Random keys for left population
vector<PopL> PopL(3);
  srand((unsigned)time(NULL));
  for (int j=0; j<3; j++){
	for (int i=0; i<numberofactivities;++i)
	{
    rn=((double) rand() / (RAND_MAX+1)) ;
	PopL[j].RK.push_back(rn);
	}
  }


For Example;
1
2
3
4
5
6
7
numberofactivities=3
PopL[1].RK[0]=0.567
PopL[1].RK[1]=0.587
PopL[1].RK[2]=0.467
PopL[2].RK[0]=0.265
PopL[2].RK[1]=0.597
PopL[2].RK[2]=0.867


and what I want is that,

First I want to give id to all RK numbers and sorting them.

For example;

1
2
3
4
5
6
7
PopL[1].RK[0]=0.567 so PopL[1].RK[0].id=2
PopL[1].RK[1]=0.587 so PopL[1].RK[1].id=3 
PopL[1].RK[2]=0.467 so PopL[1].RK[2].id=1

PopL[2].RK[0]=0.265 so PopL[2].RK[0].id=1
PopL[2].RK[1]=0.597 so PopL[2].RK[1].id=2
PopL[2].RK[2]=0.867 so PopL[2].RK[2].id=3


ids will given by starting small one to bigger one.
I just thing about nested vectors inside structure but I couldn't do.

Thank you
Last edited on
It looks like your RK should be a vector of records (value/id) rather than just a double.
1
2
3
4
5
6
7
8
9
10
struct RKRec
{
    double value;
    size_t id;
};

struct PopL
{
	vector<RKRec> RK; //For Random Key
};
The id's resemble to the ordering, i.e. smaller id <=> smaller .RK value?

If you want this id field you need to add it to your struct:
1
2
3
4
5
6
7
8
9
10
11
12
13

struct RandomKeyAndId
{
  double randomValue;
  int id;
}; 

struct PopL{
		vector<RandomKeyAndId> RK;
};
  // adjust the rest


EDIT: use the struct like kbw suggested

The sorting then can be done with an algorithm:
http://www.cplusplus.com/reference/algorithm/sort/
(or use stable_sort if it makes a difference)
Provide a custom compare function or functor (see the example on the link above) and it should do what you intend.

But if you want to "randomize" a given set of elements, you can do this directly:
http://www.cplusplus.com/reference/algorithm/random_shuffle/
Last edited on
Topic archived. No new replies allowed.