【问题标题】:Writing custom std::set comparator for object containing array in c++在 C++ 中为包含数组的对象编写自定义 std::set 比较器
【发布时间】:2011-11-29 09:09:19
【问题描述】:

我试图在这里让我的问题变得简单。我有一个以 int 数组作为成员变量的结构。

struct elem
{
    elem (int a, int b, int c) {id[0]=a; id[1]=b; id[2]=c;}
    int id[3];
};

我想将 elem 指针放入 std::set 中,并且稍后我想使用 find() 从该集合中搜索特定对象,因此我想为此 std::set 提供自定义比较器。

struct compare
{
    bool operator() (elem *one, elem *two )
    {
            // logic 
    }
};

int main(int argc, char* argv[])
{
    std::set< elem *, compare> elemSet;
    std::set< elem *, compare>::iterator itr;

    elem ob1(2,5,9), ob2(5,9,7), ob3(4,3,7);

    elemSet.insert(&ob1);
    elemSet.insert(&ob2);
    elemSet.insert(&ob3);

    elem temp(4,3,7);
    itr = elemSet.find(&temp);

    if(itr != elemSet.end())
    {
        cout << endl << (*itr)->id[0] << " " << (*itr)->id[1] << " " << (*itr)->id[2]; 
    }

    return 0;
}

您能帮我了解比较器的逻辑吗?任何大小的数组都有通用逻辑吗?

【问题讨论】:

  • 您需要什么样的帮助?只有你应该知道 operator less 应该为你的班级做什么
  • 只要使用vector,它就有你需要的一切。
  • 你想要比较的语义是什么?
  • @v01d - 我不能使用向量,因为元素的数量可以超过 200 万..
  • 我认为如果你有足够的内存用于数组,使用向量是没有问题的。我可能是错的,只是不明白这个元素计数的数组将如何存在,而向量不会?

标签: c++ stl-algorithm


【解决方案1】:

由于std::set(和std::map 及其multi 变体)需要strict-weak ordering,因此您需要通过比较器提供该排序。严格的弱排序要求

(x < x) == false
(x < y) == !(y < x)
((x < y) && (y < z)) == (x < z)

对于具有许多成员的类,实现起来可能会很复杂(如果您愿意,数组只是成员的集合)。

this question of mine 中,我询问通过tupletie 实现严格-弱排序是否明智,这使得它非常容易:

struct compare
{
    bool operator() (elem const* one, elem const* two )
    {   // take 'tie' either from Boost or recent stdlibs
        return tie(one->id[0], one->id[1], one->id[2]) <
               tie(two->id[0], two->id[1], two->id[2]);
    }
};

还请注意,我将参数作为指向const 的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2015-03-09
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多