将用户定义的类型(structs)与set等容器类一起使用

Using user defined types (structs) with container classes like set

本文关键字:set 容器类 一起 定义 用户 类型 structs      更新时间:2023-10-16

我对C++非常陌生,我正在尝试使用一个用户定义的类型,一个结构,以及一个容器类,在本例中是一个Set。

我知道,要存储无法使用内置关系运算符进行比较的用户定义类型的元素,我需要编写一个比较回调函数,并将其传递给Set构造函数。不过,我不知道这是什么语法。

我在.cpp文件中定义了这个:

Set<struct> included;

然后在头文件中定义:

struct pointT { 
int row; 
int col; 
bool operator==(PointT p1, PointT, p2) {
    return p1.x == p2.x && p1.y == p2.y;
}
};

这就是我需要做的全部吗,还是我在这里错过了一些重要的事情,因为代码似乎无法编译,因为类型无法识别?

我在这个网站上寻找过类似的答案,但我找不到任何具体和明确的答案。如有任何帮助,我们将不胜感激。

首先,为类选择一个名称;您称它为pointTPointTstruct(这甚至不是一个有效的名称)。我就叫它point,因为我不喜欢名字上奇怪的装饰。

然后您需要决定成员名称:它们是rowcol还是xy?我会选择第一个。

要将其存储在std::set中(或者通常将其用作标准关联容器中的键),您需要operator<,而不是operator==,因为关联键是按顺序排列的。这可以是具有一个参数的成员函数(this是左侧操作数,参数是右侧操作数):

struct point {
    int row;
    int col;
    bool operator<(point const & rhs) {
        return std::tie(row, col) < std::tie(rhs.row, rhs.col);
    }
};

或具有两个参数的非成员:

bool operator<(point const & lhs, point const & rhs) {
    return std::tie(lhs.row, lhs.col) < std::tie(rhs.row, rhs.col);
}

请注意,我的示例实现需要C++11<tuple>头,并假设您想要字典排序(或者不特别关心排序)。如果你被困在过去,那么你需要自己写;类似于:

bool operator<(point const & lhs, point const & rhs) {
    if (lhs.row < rhs.row) return true;
    if (rhs.row < lhs.row) return false;
    return lhs.col < rhs.col;
}

如果Set的行为不像标准的关联容器,那么它可能有其他要求;但我猜不出它们可能是什么。你必须查阅该类的文档。

您可以尝试以下操作:

#include <iostream>
#include <set>
namespace point {
    struct PointT {
        int x;
        int y;
    };
    bool operator==(const PointT& p1, const PointT& p2) {
        return p1.x < p2.x  ||  (p1.x == p2.x  &&  p1.y < p2.y);
    }
    bool operator<(const PointT& p1, const PointT& p2) {
        return p1.x < p2.x  &&  p1.y < p2.y;
    }
    bool operator<=(const PointT& p1, const PointT& p2) {
        return p1 < p2  ||  p1 == p2;
    }
    bool operator>(const PointT& p1, const PointT& p2) {
        return p2 < p1;
    }
    bool operator>=(const PointT& p1, const PointT& p2) {
        return p2 < p1  ||  p1 == p2;
    }
}

int main()
{
    using namespace point;
    std::set<PointT> s{ { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 1, 2 } };
    for (const auto& e : s) std::cout << "(" << e.x << "," << e.y << ")" << std::endl;
    return 0;
}