簡體   English   中英

使用集合測試關系的對稱性

[英]Test for symmetry in relation using sets

我正在使用類型為unsigned typedef pair<unsigned, unsigned> OP;有序對typedef pair<unsigned, unsigned> OP; ,以及有序對的typedef set<OP> SOP

我程序的最終目標是檢查set(relation)是否為等價關系。

我的問題:我已經設法檢查集合是否自反,但是目前我正在嘗試檢查集合(關系)中的有序對是否對稱。 我目前已經構造了兩個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();}) ;
}

在線演示2

更酷的是,如果您將其設為模板,則不僅可以與unsigned一起使用,而且可以與其他任何類型一起使用:

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(無符號長長)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM