使用集合测试对称性的对称性

Test for symmetry in relation using sets

本文关键字:对称 测试 集合      更新时间:2023-10-16

我正在使用订购的成对的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(无签名长)