是否可以更改C++ std :: set的比较器?

blu*_*cat 5 c++ set comparator

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

最初我使用std :: set作为我数据的容器并实现了2个比较器,希望我可以动态更改集合的比较器,导致数据量很大,将它从一个集合复制到一个不是一个好主意.另外..我只是想不时使用不同的比较器对它进行排序.这是可能的,或者正确的方法是什么?

xto*_*ofl 6

您必须std::set在施工时指定比较器.

作为解决方案,我会维护两个"索引"集,每个集都指实际集合.这将产生最大的灵活性.为了把所有东西放在一起,我建议你把它包装在一个单独的类中:

// 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() );
    }
};
Run Code Online (Sandbox Code Playgroud)

Boost库有这样一个类:Multiindex.