gpt4 book ai didi

c++ - 如何使用 const getter 对 std::set 进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:08 27 4
gpt4 key购买 nike

我有一个 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&’

最佳答案

首先,您无法对 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());

关于c++ - 如何使用 const getter 对 std::set 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com