c++ - 在 C++ 中为包含数组的对象编写自定义 std::set 比较器

标签 c++ stl-algorithm

我想在这里简化我的问题。我有一个以 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;
}

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

最佳答案

由于 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 的指针。

关于c++ - 在 C++ 中为包含数组的对象编写自定义 std::set 比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8308204/

相关文章:

c++ - 如何将 override 关键字添加到大型 C++ 代码库?

c++ - 在 C++ 编译时从 CSV 创建 vector

c++ - 如何将成员函数传递给另一个成员函数中使用的函数?

c++ - C++ 中的数组和长度

c# - 初始化 C# IntPtr 以接受来自非托管 C++ DLL 的数据?

c++ - 为什么 std::count_if 返回有符号值而不是无符号值?

c++ - 对 std::unique 实现感到困惑?

c++ - 使用算法查找自定义数据 vector 中的最大值和最小值

c++ - std::sort 在 std:vector of pointers 上失败

c++ - 有没有插入然后排序的替代方法