How to sort a std::set with const getters

前端 未结 1 1563
情书的邮戳
情书的邮戳 2021-01-18 14:48

I have a std::set container whose elements are objects of the following class:

class LaneConnector {
public:

    const Lane* getLaneFrom() const {
        r         


        
相关标签:
1条回答
  • 2021-01-18 15:06

    First, you cannot sort an std::set. It is a sorted structure, sorting happens upon construction or insertion.

    Second, you can construct an std::set with your own sorting functor, and you can avoid unnecessary const_casts by making it take const pointers:

    struct MyLaneConectorSorter {
      bool operator() (const LaneConnector* lhs, const LaneConnector* rhs) const
      {
        // you may want to put some null pointer checks in here
        const Lane* a = lhs->getLaneFrom();
        const Lane* b = rhs->getLaneFrom();
        return a->getLaneID() < b->getLaneID();
      }
    };
    

    and instantiate the set like this:

    std::set<LaneConnector*, MyLaneConectorSorter> s(MyLaneConectorSorter());
    

    or, if you want to construct it from a different set, with a different ordering,

    std::set<LaneConnector*> orig = ..... ;
    ....
    std::set<LaneConnector*, MyLaneConectorSorter> s(orig.begin(), orig.end(), MyLaneConectorSorter());
    
    0 讨论(0)
提交回复
热议问题