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++?
Asked
Active
Viewed 188 times
-2
-
6`std::sort` passing a compare function: see http://en.cppreference.com/w/cpp/algorithm/sort (3) – Richard Critten Jan 08 '18 at 19:07
-
Are you asking how to sort an array, or how to compare the vectors? – Caleb Jan 08 '18 at 19:08
1 Answers
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
-
-
Or using a lambda exp. : `std::sort(V[x].begin(), V[x].end(), [](std::pair
a, std::pair – mholle Jan 08 '18 at 19:18b){ return a.second < b.second; });` -
-
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