Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用集合检验关系的对称性_C++_Algorithm_Set_Relationship_Discrete Mathematics - Fatal编程技术网

C++ 用集合检验关系的对称性

C++ 用集合检验关系的对称性,c++,algorithm,set,relationship,discrete-mathematics,C++,Algorithm,Set,Relationship,Discrete Mathematics,我正在处理类型unsignedtypedef pair OP的有序对,以及一组有序对typedef set SOP 我的程序的最终目标是检查集合(关系)是否是等价关系 我的问题是:我已经设法检查了一个集合是否是自反的,但目前我正在尝试检查集合(关系)中的有序对是否是对称的。我目前已经构建了两个for循环来比较有序对,但是在比较中遇到了一个死胡同 我的代码: for (auto it3 = sop.begin(); it3 != sop.end(); it3++) { // loop throug

我正在处理类型unsigned
typedef pair OP的有序对,以及一组有序对
typedef set 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;
                }
            }
        }
    }

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

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

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

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

更酷的是,如果您将其作为模板,不仅可以使用未签名的,还可以使用任何其他类型:

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();}) ;
}
模板
布尔是对称的(设置sop){
返回(sop.cbegin()、sop.cend()、的所有内容,
[&sop](auto&x){返回x.first==x.second | | sop.find({x.second,x.first})!=sop.end();});
}

请根据需要在此处提供一个复制问题的示例,并详细说明代码的意外行为(输入、实际输出、预期输出、调试工作)。