C ++: std :: map sorting
I'm new to C ++ and this question may seem obvious to a lot of people.
If I write something like
std::map<int, double> m;
- Is it possible to sort m according to int order?
- Do I need to define a comparison class for forced sorting?
For example,
class own_int_less : public binary_function<int, int, bool>
{
public:
bool operator()( const double &left, const double &right ) const
{
return (abs(left - right) > epsilon) && (left < right);
};
double epsilon;
};
- When does sorting take place? I mean, does the sort function call the sort every time I insert something into the map? Or is it called before iterating through the map?
Thank.
+3
source to share
1 answer
Is it possible to sort m according to int order?
Yes. The default comparator std::less<Key>
, which in your case std::less<int>
, which uses <
as expected.
Do I need to define a comparison class for forced sorting?
No, because the previous answer was yes!
When does sorting take place?
A typical implementation map
uses a comparator to insert a new item at the desired location. The comparator is also used when performing searches.
+10
source to share