2014-11-06 37 views
0

我有兩個結構類似這樣C++比較兩個結構,顯示有什麼區別

struct Activity { 
int id; 
string Description; 
int parameter1; 
int parameter2; 
int parameter3; 
int parameter4; 
etc... 
} 

Activity A1; 
A1.id=0; 
A1.parameter1=50; 

Activity A2; 
A2.id=0; 
A2.parameter1=55; 

我想對它們進行比較,顯示哪些成員是不同的? 在這種情況下是這樣的:

paameter1是不同的...

感謝

+1

'if(A1.parameter1!= A2.parameter1)...' – Jon 2014-11-06 23:16:58

+3

您嘗試過什麼嗎?顯示你的嘗試。 – 2014-11-06 23:18:04

+0

我認爲OP在dotnet或java中要求類似Reflection的東西。但遺憾的是在C/C++中沒有這樣的東西。 – holgac 2014-11-15 11:18:48

回答

3

要做到這一點可能是寫裏面的結構public方法將通過參數傳遞與結構本身比較的最佳解決方案。

這看起來像這樣

struct Activity { 
    int id; 
    string Description; 
    int parameter1; 
    int parameter2; 
    int parameter3; 
    int parameter4; 
    etc... 

    public: 
    bool compare(const Activity& param) 
    { 
     //...compare structs here like: 
     if (id != param.id) 
     //write something 

     //etc... 

     //at the end you can also return bool that indicates that structs are equal or not 
     return true; 
    } 
} 

,除非你寫更多的比較方法這顯然只能使用兩個相同的類的工作,但它可能是很難比較兩個不同的結構。

還有其他方法可以比較兩個變量(包括結構)。對於這個memcmp()函數可以使用,但它不會直接告訴你,哪些字段是不同的。

根據@Tony_D的說法編輯。

+1

+1,但應該是'bool compare(const Activity&param)const'(如果打擾追蹤布爾結果)。 'const&'避免了'param'的不必要的緩慢拷貝構造,並且尾部的'const'可以讓你使用函數來比較一個'const'' Activity'對象與另一個對象。 – 2014-11-06 23:56:25

+0

謝謝,這是因爲我在結構中有很多成員,並且我不會爲每個成員編寫比較。 – Gpouilly 2014-11-07 00:03:26

+0

@Gpouilly你必須寫每個比較 – 2014-11-07 00:46:40