I have a std::set
containing values of the type of std::pair<T1, T2>
with order by first value of the pair:
struct Comparator
{
bool operator() (const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs) const
{
return lhs.first < rhs.first;
}
}
My definition is std::set<std::pair<T1, T2>, Comparator> s
.
But when I try to insert pair with the same first value with element inserted to the set before (second value is different). The set does not insert it.
I'd like to have std::set
that treats elements as equal only where second value of the pair is equal (or first and second are equal). How to do that??
PS I don't want to use boost library.
But when I try to insert pair with the same first value with element inserted to the set before (second value is different). The set does not insert it.
Well, that's what you've asked for. Your comparator only looks at the first
member and a std::set
does not allow for duplicate entries. I guess that you probably want to sort by the first
member first and if that is equal, by the second
. Hence, change your comparator to something like this:
struct Comparator
{
bool operator() (const std::pair<T1, T2>& lhs,
const std::pair<T1, T2>& rhs) const
{
if (lhs.first == rhs.first)
return lhs.second < rhs.second;
else
return lhs.first < rhs.first;
}
}
Note that this is what the default operator <
for std::pair
would do anyway so if you want this particular ordering, simply use the default.
Thanks for replies. So, let's make it task easier: 1) Sort ordering: lhs.first < rhs.first (so I'd like to sort by first element of the pair). 2) The set should treat pair as equal (and forbid to insert) ONLY when: lhs.first == rhs.first && lhs.second == rhs.second.
I think it's clear what I'd like to have.
I'm writing application using CV Open library. My set is defined as:
std::set<std::pair<double, cv::Point>, QComparator> s;
where QComparator
is:
struct QComparator
{
bool operator() (const std::pair<double, cv::Point>& lhs, const std::pair<double, cv::Point>& rhs) const
{
return lhs.first < rhs.first;
}
};
PS I'll explain what is cv::Point in CV library:
typedef Point_<int> Point2i;
typedef Point2i Point;
How to do that?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.