5

我有一个 std::set 容器,其元素是以下类的对象:

class LaneConnector {
public:

    const Lane* getLaneFrom() const {
        return From;
    }
    const Lane* getLaneTo() const {
        return To;
    }

private:

    Lane* From;
    Lane* To;
}

我的比较器功能如下:

struct MyLaneConectorSorter {
  bool operator() (LaneConnector * c, LaneConnector * d)
  {
      Lane* a = const_cast<Lane*>(c->getLaneFrom());
      Lane* b = const_cast<Lane*>(d->getLaneFrom());
      return (a->getLaneID() < b->getLaneID());
  }
} myLaneConnectorSorter;

现在,当我尝试使用以下命令对集合中的元素进行排序时:

//dont panic, the container just came through a const_iterator of a std::map :)
const std::set<LaneConnector*> & tempLC = (*it_cnn).second;
std::sort(tempLC.begin(), tempLC.end(), myLaneConnectorSorter);

我从以下几行开始疯狂地出错,如果你帮我解决这个问题,我会很感激。谢谢:

/usr/include/c++/4.6/bits/stl_algo.h: In function ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_const_iterator<LaneConnector*>, _Compare = {anonymous}::MyLaneConectorSorter]’:
/home/.../dev/Basic/shared/conf/simpleconf.cpp:1104:65:   instantiated from here
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: error: no match for ‘operator-’ in ‘__last - __first’
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: note: candidates are:
/usr/include/c++/4.6/bits/stl_iterator.h:321:5: note: template<class _Iterator> typename std::reverse_iterator::difference_type std::operator-(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
/usr/include/c++/4.6/bits/stl_iterator.h:378:5: note: template<class _IteratorL, class _IteratorR> typename std::reverse_iterator<_IteratorL>::difference_type std::operator-(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note: std::ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note:   no known conversion for argument 1 from ‘std::_Rb_tree_const_iterator<LaneConnector*>’ to ‘const std::_Bit_iterator_base&’
4

1 回答 1

10

首先,您不能对std::set进行排序。它是一个排序结构,排序发生在构造或插入时。

其次,您可以std::set使用自己的排序仿函数构造一个,并且可以const_casts通过使其采取来避免不必要的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();
  }
};

并像这样实例化集合:

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

或者,如果你想从不同的集合中构建它,具有不同的顺序,

std::set<LaneConnector*> orig = ..... ;
....
std::set<LaneConnector*, MyLaneConectorSorter> s(orig.begin(), orig.end(), MyLaneConectorSorter());
于 2012-09-25T05:39:39.133 回答