Reputation: 3044
I'm trying to sort std::vector<std::pair<float, std::string>>
in ascending order.
Although using std::sort
works, I found out the strings affect the order if the floats have the same values.
I would like to sort the vector regardless of the string so the former element always gets located first than latter ones.
My Code :
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::pair<float, std::string>> vec;
vec = {{1, "e"}, {1, "d"}, {1, "c"}, {1, "b"}, {1, "a"}};
std::sort(vec.begin(), vec.end());
for (auto i : vec)
std::cout << i.first << ", " << i.second << '\n';
}
The Result I Get : (alphabetical order when value ties)
1, a
1, b
1, c
1, d
1, e
Program ended with exit code: 0
The Result I Want : (former element first when value ties)
1, e
1, d
1, c
1, b
1, a
Program ended with exit code: 0
Upvotes: 2
Views: 1459
Reputation: 22229
std::pair
has it's comparing operators overloaded (See the reference)
By default, operator <
for std::pair
compares first elements, if they are equal, then second elements.
You should provide your own predicate and use std::stable_sort
to preserve the order of elements if first elements in pair are equal.
std::stable_sort(vec.begin(), vec.end(),
[](const auto& a, const auto& b){return a.first < b.first;});
Upvotes: 11
Reputation: 5880
You can provide a compare function to std::sort. Like
std::sort(vec.begin(), vec.end(), comp);
In your case the compare function can be:
bool comp(const std::pair<float, std::string>&a, const std::pair<float, std::string>&b){
if(a.first == b.first) return 0;
else return a.first < b.first;
}
Upvotes: -1
Reputation: 464
You are probably searching for std::stable_sort
. It sorts elements while preserving the order of equivalents.
Upvotes: 0