简体   繁体   English

C ++:std :: map排序

[英]C++: std::map sorting

I am a newbie to C++, and this question may seem obvious to a lot of people. 我是C ++的新手,这个问题对于很多人来说似乎都很明显。

If I write something like 如果我写这样的话

std::map<int, double> m;
  • Is m guaranteed to be sorted according to int order? 是否保证m根据int顺序排序?
  • 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. 谢谢。

Is m guaranteed to be sorted according to int order? 是否保证m根据int顺序排序?

Yes. 是。 The default comparator is std::less<Key> , which in your case is std::less<int> , which just uses < as expected. 默认比较器为std::less<Key> ,在您的情况下为std::less<int> ,它按预期使用<

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. 典型的map实现使用比较器将新元素插入正确的位置。 The comparator is also used when doing a lookup. 查找时还使用比较器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM