千年银杉

如何禁止STL map 自动排序

  最近在做一个SPC/SQC 的项目。其中有一处用到了stl map。得到了一个小小的心得,分享给大家。

 

我们知道,在向map中插入数据对时候,map中的元素将按照一定的顺序被插入到对应的节点上,换句话说,从map的头开始顺序地读取数据,其数据的顺序将不同于你插入时候的顺序, 例子如下:

 

  std::map<double,int> dnMap;

 

  dnMap[10.0] = 1;

  dnMap[2.9]   = 2;

  dnMap[20.4] = 3;

 

  std::map<double,int>::iterator it = dnMap.begin();

  for(; it != dnMap.end();++it)

  {

        std::pair<double,int> _p = *it;

        std::cout <<"Key =" <<_p.first<<"  Value = "<< _p.second<< endl;

  }

 

 输出的顺序将是:

    

          Key =            Value =

 

           2.9               2

           10.0             1

            20.4             3

 

如果map的键是用户自定义的类型T,那么你还必须在T中实现比较运算符,至于具体的细节这里就不说了。

 

但是如果你觉得map对你很合适,但是就是希望插入map中的数据保持最初插入时候的顺序,这时候怎么办?

 

让我们来看看stl中map的 声明形式 (http://www.sgi.com/tech/stl/Map.html

 

                       map<Key, Data, Compare, Alloc>

 

注意第三个参数

Compare : The key comparison function, a Strict Weak Ordering whose argument type is key_type; it returns true if its first argument is less than its second argument, and false otherwise. This is also defined as map::key_compare.

 

其作用就是比较Key的大小,按照一定的顺序确定map节点的顺序,我们当然就可以定制这个函数对象以实现我们想要的的排序规则。

 

好了,废话说了不少,我的做法是

 

template<class T>
struct DisableCompare :public std::binary_function<T,T,bool>
{
    bool operator()(T lhs,T rhs)  const
    {
        return true;
     }
};

 

 

这样来使用定制化的map :

 

 std::map<double,int,DisableCompare<double> > sMap;
 sMap[10.9] = 1;
 sMap[3.5]  =  2;
 sMap[30.0] = 3;
 sMap[2.4]  =  4;

 

就可以保持数据插入时候的顺序了。

posted on 2013-04-08 19:30  千年银杉  阅读(13608)  评论(5编辑  收藏  举报

导航