【问题标题】:Test for symmetry in relation using sets使用集合测试关系的对称性
【发布时间】:2019-03-19 18:52:35
【问题描述】:

我正在使用无符号类型的有序对typedef pair<unsigned, unsigned> OP;,以及有序对集合typedef set<OP> SOP;。

我的程序的最终目标是检查集合(关系)是否是等价关系。

我的问题:我已经设法检查一个集合是否是自反的,但目前我正在尝试检查该集合(关系)中的有序对是否是对称的。我目前已经构建了两个 for 循环来比较有序对,但在我的比较中遇到了死胡同。

我的代码:

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;
                }
            }
        }
    }

【问题讨论】:

  • 请在此处提供一个minimal reproducible example 以重现您的问题,并具体说明您的代码的意外行为(输入、实际输出、预期输出、您的调试工作)。

标签: c++ algorithm set relationship discrete-mathematics


【解决方案1】:

你的循环逻辑完全有缺陷。

内部 while 既不改变 it3 也不改变 it4。因此,它要么返回 false,要么永远循环。此外,内部 for 循环没有利用集合是有序的这一事实。

您正在寻找的测试要简单得多

循环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; 
}

Online demo

如果你被允许使用算法库,甚至还有一个更酷的解决方案:

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();}) ;
}

Online demo 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();}) ;
}

Online demo 3 (with unsigned long long)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多