是否可以更改C ++ std :: set的比较器? [英] Is it possible to change the comparator of a C++ std::set?

查看:74
本文介绍了是否可以更改C ++ std :: set的比较器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组数据,在某些情况下,我需要以一种方式对它们进行排序,而在某些情况下,则需要以另一种方式对它们进行排序。例如,假设数据集是一组字符串,{ abc, dfg,...}。有时我需要按字母顺序对它们进行排序,有时还需要比较它们的长度。



最初,我使用std :: set作为数据的容器并实现了2个比较器,希望我可以即时更改集合的比较器,因为数据巨大,将它从一个集合复制到另一个集合不是一个好主意。我只想不时使用不同的比较器对其进行排序。这可能是什么,还是正确的方法呢?

解决方案

您必须指定的比较器作为解决方案,我将维护两个索引集,而每个索引集均指向实际集合。这将产生最大的灵活性。为了使所有内容保持一致,建议您将其包装在一个类中:

  //以进行编译,调试等。 。,但是理想的
//要抓住这个想法
//注意:只要集合
//调整大小/重新分配等等,就维护索引对象...
//这样不要自己写,请使用现有的库:)
template<类型名T,类型名comp1,类型名comp2>
struct MultiIndex {
std :: deque< T>采集;
std :: set< T *,comp1> index1;
std :: set< T *,comp2> index2;

void insert(const T& t){
collection.push_back(t);
index1.insert(& collection.back());
index2.insert(& collection.back());
}
};

Boost库具有此类:多重索引


I have a set of data which in some occasion I need to sort them in one way and some occasion in another way. For example, suppose the data set is a set of strings,{"abc", "dfg",...}. Sometimes I need to sort them in alphabetic order and sometimes by comparing their length.

Initially I used std::set as a container of my data and implemented 2 comparators, hoping that I can change the comparator of the set on the fly, cause the data is huge and it's not a good idea to copy it from one set to another..I just want to sort it using different comparators from time to time. Is this possible or what's the right way to do it?

解决方案

You have to specify the comparator of std::set at construction time.

As a solution, I would maintain two 'index' sets instead, each referring to the actual collection. This would yield the greatest flexibility. To keep everything together, I suggest you wrap it up in a single class:

// to be compiled, debugged etc..., but ideal
// to grab  the idea
// caveats: maintain the index objects whenever the collection
// gets resized/reallocated etc...
// so not to be written yourself, use an existing library :)
template< typename T, typename comp1, typename comp2 >
struct MultiIndex {
    std::deque<T> collection;
    std::set<T*, comp1> index1;
    std::set<T*, comp2> index2;

    void insert( const T& t ){
       collection.push_back(t);
       index1.insert( &collection.back() );
       index2.insert( &collection.back() );
    }
};

Boost library has such a class: Multiindex.

这篇关于是否可以更改C ++ std :: set的比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆