0

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

3
Contributors
5
Replies
6
Views
8 Years
Discussion Span
Last Post by daviddoria
0

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;
0

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;
	}
}
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.