3

I am a newbie to C++, and this question may seem obvious to a lot of people.

If I write something like

std::map<int, double> m;
  • Is m guaranteed to be sorted according to int order?
  • Is it necessary to define a comparitor class to enforce the 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 is the sorting actually occurred? I mean does the sorting function get called every time I insert something into the map? Or does it get called before I iteration through the map?

Thanks.

2
  • 3
    You defined a binary_function<int, int, bool>, but your operator() is taking two const double & as parameters... Commented Apr 1, 2012 at 14:00
  • Be careful to initialize your member variables. (epsilonis never initialized in your example). Commented Apr 2, 2012 at 8:00

1 Answer 1

10

Is m guaranteed to be sorted according to int order?

Yes. The default comparator is std::less<Key>, which in your case is std::less<int>, which just uses < as expected.

Is it necessary to define a comparitor class to enforce the sorting?

No, because the previous answer was "yes"!

When is the sorting actually occurred?

A typical map implementation uses the comparator to insert a new element into the correct location. The comparator is also used when doing a lookup.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.