-2

I have a pair of array of vectors {V[x].push_back(make_pair(y,w));} I want to sort it by the second element ie. by w.How could it be done in c++?

1 Answers1

0

You will need to pass the comparing function as the third parameter to the sort function. Like you mentioned your vector is something of the form:

 {V[x].push_back(make_pair(y,w));}

Then the comparing function will look like:

bool greaterThan( pair<int,int> lx, pair<int,int> rx ){
    return lx.second < rx.second; //change here for different criterias
}

//used as
sort(V[x].begin(), V[x].end(), greaterThan);
VishalTheBeast
  • 459
  • 3
  • 9
  • I am sorry I didn't understand. Edit: Corrected – VishalTheBeast Jan 08 '18 at 19:18
  • Or using a lambda exp. : `std::sort(V[x].begin(), V[x].end(), [](std::pair a, std::pair b){ return a.second < b.second; });` – mholle Jan 08 '18 at 19:18
  • Actually you need to pass `greaterThan` without parenthesis. – mholle Jan 08 '18 at 19:21
  • You are right @nngmg. If using c++ provided `greater` comparator function, then only we need those parenthesis. Thanks. – VishalTheBeast Jan 08 '18 at 19:22
  • @VishalTheBeast actually I had the undirected graph with v[x].push_back(make_pair(y,w)) and v[y].push_back(make_pair(x,w)) and i wanted to sort by w. Should sort(V[x].begin(), V[x].end(), greaterThan); work or i should pass y in V? – twinkle kapor Jan 08 '18 at 19:57
  • You may be wanting to sort your vertices by weights. It depends on your algorithm but you can sort them this way without any problem, I guess. – VishalTheBeast Jan 08 '18 at 20:00