问题
my code are having some problems on my Visual Studio 2010 but not on DevCPP. Heres the situation, I used C++ STL set
in my code to insert pair<string, double>
but then I want my set
to sort them using the value instead of the key, so I used a custom comparator to achieve this.
struct sortPairSecond
{
bool operator()(const pair<string, double> &lhs, const pair<string, double> &rhs)
{
return lhs.second >= rhs.second;
}
};
The code works fine in DevCPP but encountered the Debug Assertion Failed on the xtree using VS2010. I did some debugging and I realize the error is caused by the use of >= in the custom comparator, eliminating the = make the code works but incorrect results as duplicate value should be allowed in my program. Therefore anyone can help me on this matter?
回答1:
Your using >=
and not >
may be invalid because it needs to be a strict ordering thus op(a,b)
and op(b,a)
cannot both be true (but they would be if they were equal).
It is just an assertion error but a set
cannot contain duplicate values. Just use a sorted vector
or you can use multiset
(and use '>')
Of course as we know the first values are unique, we can extend the predicate when the second value is equal to compare the first. That will guarantee you unique values and then you can still use std::set
.
struct sortPairSecond
{
bool operator()(const pair<string, double> &lhs, const pair<string, double> &rhs) const
{
return (lhs.second > rhs.second) || (lhs.second == rhs.second && lhs.first > rhs.first) ;
}
};
Essentially, don't try to "break" what std::set
is intended to be used for by trying to manipulate your predicate.
来源:https://stackoverflow.com/questions/13375885/visual-studio-assertion-failed-on-c-set-comparator