使用集合测试对称性的对称性
Test for symmetry in relation using sets
我正在使用订购的成对的UNSIGNED typedef pair<unsigned, unsigned> OP;
,以及有序对 typedef set<OP> SOP
;。
我程序的最终目标是检查集合(关系)是否是等价关系。
我的问题:我已经设法检查了一组反射性,但目前我正在尝试检查集合中的订购对(关系)是否对称。我目前已经构建了两个循环,以将订购的对相互比较,但在我的比较中却打出了终点。
我的代码:
for (auto it3 = sop.begin(); it3 != sop.end(); it3++) { // loop through each pair in set
for (auto it4 = sop.begin(); it4 != sop.end(); it4++) { // compare with other pairs
// make sure first and second items in pair are different
while (it3->first != it3->second) {
//If the case is that there is not an instance of
//symmetric relation return false
if (!((it3->first == it4->second) && (it3->second == it4->first))) {
return false;
}
}
}
}
您的循环逻辑完全有缺陷。
内部虽然不会更改IT3和IT4。因此,要么它将返回false,要么它将永远循环。此外,循环的内部循环并不是订购集合的事实。
您要寻找的测试更简单
这足以在sop
上循环,如果对称也在集合中,请检查每个项目。如果不是,那不是对称关系。如果所有人都成功地找到了反面,那很好:
bool is_symetric (SOP sop) {
for (auto it3 = sop.begin(); it3 != sop.end(); it3++) { // loop through each pair in set
if (it3->first != it3->second) {
if (sop.find({it3->second,it3->first })==sop.end()) {
return false;
}
}
}
return true;
}
在线演示
如果允许您使用算法库:
,甚至还有一个凉爽的解决方案bool is_symetric (SOP sop) {
return all_of(sop.cbegin(), sop.cend(),
[&sop](auto &x){ return x.first==x.second || sop.find({x.second,x.first })!=sop.end();}) ;
}
在线演示2
甚至更酷的是,如果您使其成为模板,不仅可以与未签名,还可以与其他类型一起使用:
template <class T>
bool is_symetric (set<pair<T,T>> sop) {
return all_of(sop.cbegin(), sop.cend(),
[&sop](auto &x){ return x.first==x.second || sop.find({x.second,x.first })!=sop.end();}) ;
}
在线演示3(无签名长)
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 尽管测试成功,CppUnit测试核心仍被丢弃.为什么
- 数据成员SFINAE的C++17测试:gcc vs clang
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么二进制搜索在我的测试中不起作用
- 从父数组测试用例构造二叉树失败
- 试图对缓存进行跨步测试,但程序并没有结束
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- OpenGL在启用深度测试时不会丢弃我的碎片
- 为测试目标创建具有不同源文件夹的文件
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- VC++本机单元测试,找不到调试符号
- 换位表导致测试失败(但在游戏中运行良好)
- 用于交叉编译和CMake的预处理器宏的单元测试
- 谷歌测试中的期望值存储在哪里
- 如何在for循环中包含两个索引值的测试条件
- 在cygwin中测试新的boost安装时出现cpp错误
- 使用结构进行反射,对称或及时的测试集
- 如何测试自反、对称或传递