将用户定义的类型(structs)与set等容器类一起使用
Using user defined types (structs) with container classes like set
我对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;
}
};
这就是我需要做的全部吗,还是我在这里错过了一些重要的事情,因为代码似乎无法编译,因为类型无法识别?
我在这个网站上寻找过类似的答案,但我找不到任何具体和明确的答案。如有任何帮助,我们将不胜感激。
首先,为类选择一个名称;您称它为pointT
、PointT
和struct
(这甚至不是一个有效的名称)。我就叫它point
,因为我不喜欢名字上奇怪的装饰。
然后您需要决定成员名称:它们是row
和col
还是x
和y
?我会选择第一个。
要将其存储在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;
}
相关文章:
- 如何正确实现容器类中元素的更改?
- C++ 用于检查容器类中是否存在函数和隐式推导规则的概念
- 容器类中的类迭代器
- 为什么 std::set 容器使用的内存比其数据大小多得多?
- 返回持有 std::mutex 锁的 RAII 容器类
- C++ 如何在容器类复制构造函数中复制分配器对象
- 如何使用迭代器设计模式为 C++ 中的包装容器类提供多个迭代器?
- 如何在模板容器类中实现复制构造函数和赋值运算符
- 对范围项使用 std::set 容器
- 在容器类中使用带有共享_ptr/unique_ptr的虚拟对象
- 在自定义容器类上反转基于范围的 for 循环
- C++ 在容器类中使用自定义比较器的排序集
- 在类组合中,使包含的类可以访问容器类变量
- 为什么 std::to_string 不支持容器类作为输入?
- 从可变参数模板容器类中调用给定可变参数的 in 和 out 方法
- 是否有不变的STL容器类
- 什么是C++中的容器类,任何人都可以举个好例子
- 支持自定义 const 本机C++容器类的"for each"
- 容器类 c++ 的循环
- 将用户定义的类型(structs)与set等容器类一起使用