I've seen that a vector can be sorted using

vector<double> V;
vector<int> Index;
V.push_back(9);
V.push_back(10);
V.push_back(8);
Index.push_back(0);
Index.push_back(1);
Index.push_back(2);
sort(V.begin(), V.end());

If I want to sort Index according to how V was sorted, there is an optional third parameter to sort() that will do this. I don't understand how to specify this third parameter. I saw an example that defined an iterator, but that was for sorting a fancier class than just doubles.

Can someone point me in the right direction?

Thanks!

David

since V is already sorted, how would I sort Index based on how V WAS sorted??

you will have to sort them both at the same time. You might have to write your own sort algorithm because I don't think std::sort will support that.

Or change the algorithm and create a structure with an int and a double member, then have a vector of these structures and sort by the double member.

struct num
{
   inb index;
   double v;
};
vector<num> array;

This is how it solved my problem for parallel sorting two vectors. I am bit of a noob and more comfortable in Fortran hence that's why I made a function rather than a struct or class. :D I have read that C++ programmers prefer not to pass vectors but rather pass the iterator, but this seems to work for me fine, albeit I only need to sort small vectors of 2 to 3 elements.

void ParallelSort( std::vector<double> &vec1, std::vector<double> &vec2, int nlength)
{
  // create a vector of pairs
  std::vector< std::pair<double,double> > combovec;
  // fill the vector of pairs with the elements of vec 1 and vec2
  for ( int it=0; it<vec1.size(); ++it ) combovec.push_back( std::make_pair( vec1.at(it),vec2.at(it) ));
  // sort the vector this will be done on the first element of a pair
  std::sort( combovec.begin(),combovec.end() );
  // overwrite the vec1 and vec2 with the sorted elements of the paris
  for ( int it=0; it<vec1.size(); ++it )
	{
		vec1.at(it) = combovec.at(it).first;
		vec2.at(it) = combovec.at(it).second;
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.