-1

Hey all I have a vector of pair. After sorting the vector (i.e. sort(v.begin(),v.end()) .....It sorts the element on the basis of first element but there is a prob with me ...as I need to keep those element of second in same order whose first element are same ...for example look the following code..

std::vector<std::pair<int, int> > v(2);
v[0].first = 1; v[1].first = 1;
v[0].second = 2; v[1].second = 0;
sort(v.begin(),v.end());
for (int i = 0; i < 2; i++)
{
    std::cout << v[i].first << " " << v[i].second << std::endl;
}

as output for the above code is

1 0
1 2

whereas i want the output as following

1 2
1 0

please help !!

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Roshan
  • 150
  • 16
  • No, this is **not** a duplicate, OP is asking for a stable sort (+ the dup is 7 years old : no need for boost anymore for this) – quantdev Aug 21 '14 at 16:34

1 Answers1

6

Use std::stable_sort (to preserve your insertion order) with a custom comparer :

std::stable_sort(std::begin(v),
                 std::end(v),
                 [](const std::pair<int, int>& p1, const std::pair<int, int>& p2) { return p1.first < p2.first; });
quantdev
  • 23,517
  • 5
  • 55
  • 88