2017-05-08 24 views
-2

我有幾個固定長度的數組,並且想要比較它們。可以在C++中比較原始內存嗎?

struct Foo 
{ 
    /// the data, not necessarily int and not necessarily length 32 
    int val[32]; 

    /// simple way 
    inline bool compare1(const NAME_CELL & rhs) const 
    { 
     for (unsigned int ui = 0; ui < 32; ++ui) 
     { 
      if (val[ui] != rhs.val[ui]) 
      { 
       return false; 
      } 
     } 
     return true; 
    } 

    /// compare memory directly instead of using a loop. Is this faster? 
    inline bool compare2(const NAME_CELL & rhs) const 
    { 
     return memcmp(val, rhs.val, 32 * sizeof(int)) == 0; 
    } 
}; 

是比較1慢,快或等於比較2?有更快的方法嗎?

+0

我假設你的意思是'memcmp'? –

+0

此外,你的標題說「C」,但你已經標記了這個「C++」 - 你在說什麼? –

+0

謝謝,更正了標題。我使用C++,但我的問題可能與C開發人員同樣相關。 – Fabian

回答

2

除非你初始化的val的元素,然後要麼方法的行爲是在標準C 未定義 ++。

除此之外,最好的方法是相信編譯器進行適當的優化。但如果您仍然有疑問,(i)描述性能,(ii)檢查生成的程序集,& c。

+0

重新初始化:爲什麼行爲未定義? val的內容是,但行爲? – James

+1

'int'可能包含陷阱表示。一個'unsigned char'數組會很好。請參閱http://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior-in-c。當然,它被標記爲C,但是一個好的起點。 – Bathsheba

+0

當然你必須在比較之前初始化Foos。沒有必要提到這一點。 – Fabian