gpt4 book ai didi

c++ - 如何使用多个键对 std::set 进行排序

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

我需要根据多个 key 将一组复制到另一组。键用于 - 共同地 - 维护集合中元素的唯一性和顺序。

我的类(class):

class LaneConnector {
public:

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

private:

Lane* From;
Lane* To;
}

我的仿函数:

struct MyLaneConectorSorter {
bool operator() (const LaneConnector* rhs, const LaneConnector* lhs) const
{

const Lane* a = lhs->getLaneFrom();
const Lane* b = rhs->getLaneFrom();

bool key1 = a->getLaneID() < b->getLaneID();
bool key2 = a->getLaneParent->ID() < b->getLaneParent->ID();
bool key2 = a->getLaneParent->getParent->ID() < b->getLaneParent->getParent->ID();
//remind you that I NEED the elements to be in ascending order of
//getLaneParent->getParent->ID() ,a->getLaneParent->ID() and then a->getLaneID()
//duplicate elements are the ones which have all three keys same and need to be discarded
return (key1 && key2 && key3); //which dont seem to be working
}
};

以及我的来源和起源集:

const std::set<LaneConnector*> src = ..... ; //the getter give me a const version
std::set<sim_mob::LaneConnector *, MyLaneConectorSorter> dest;

以及我如何填写:

for(std::set<sim_mob::LaneConnector*>::iterator it = tempLC.begin(); it != tempLC.end(); it++)
{
dest.insert(*it);//I know I can insert it right at the time of declaration, but keep it like this for now...please
}

非常感谢您的帮助。

最佳答案

自从获得 operator<对于多个测试,正确是相当困难的,我主张my way of doing this with tuple (在这种情况下使用 make_tuple 而不是 tie 因为我们正在处理从函数返回的临时对象):

#include <tuple>

struct MyLaneConectorSorter {
bool operator() (const LaneConnector* lhs, const LaneConnector* rhs) const
{
const Lane* a = lhs->getLaneFrom();
const Lane* b = rhs->getLaneFrom();
auto const* pa = a->getLaneParent();
auto const* pb = b->getLaneParent();

return std::make_tuple(a->getLaneID(), pa->ID(), pa->getParent()->ID()) <
std::make_tuple(b->getLaneID(), pb->ID(), pb->getParent()->ID())
}

这应该有效,您可以获得 tuplemake_tuple也来自 Boost,如果您的编译器还没有提供它们的话。

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

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