0

私がやりたいのは、C++ の同じ構造体の 2 つの変数に対するビット単位の XOR です。

    D[i] ^= D[j];

ここで、D は文字列、int などを含む配列です。

ただし、コンパイラは文句を言います (ここでは整数配列をインデックスとして使用しています。つまり、D[dInd[u]]^=...):

Description Resource    Path    Location    Type
no match for ‘operator^=’ in ‘*(D + ((long unsigned int)(((long unsigned int)
(*(dInd + ((long unsigned int)(((long unsigned int)u) * 4ul))))) * 2808ul))) 
^= *(D + ((long unsigned int)(((long unsigned int)(*(dInd + ((long unsigned 
int)(((long unsigned int)i) * 4ul))))) * 2808ul)))’

ビット単位の XOR を実現するためにこの行を修正する方法を知っている人はいますか?

ヒントは非常に高く評価されています。前もって感謝します、乾杯 - アレックス

4

2 に答える 2

3

構造体のメンバーをオーバーロードします。

struct X
{
   X& operator ^= (const X& other)
   {
       //...
       return *this;
   }
};
于 2012-07-17T09:42:08.907 に答える
1

少しトリッキーです...構造をXOR可能なタイプのデータの連続した領域として再解釈することによってXORするか、各データメンバーを順番にXORする方法を考えることができます。どちらのアプローチにも考慮する必要がある問題があり、どちらが最適かは、それを行う理由によって異なります。

例えば:

struct X
{
    X& operator^=(const X& rhs)
    {
        // WARNING: this won't follow pointers to "owned" data
        unsigned char* p = (unsigned char*)this;
        unsigned char* q = (unsigned char*)&rhs;
        size_t size = sizeof *this;
        while (size--)
            *p++ ^= *q++;
    }
};

    X& operator^=(const X& rhs)
    {
        my_int ^= rhs.my_int;

        for (size_t i = 0; i < sizeof my_int_array / sizeof my_int_array[0]; ++i)
             my_int_array[i] ^= rhs.my_int_array[i];

        // WARNING: this won't XOR the string object's embedded data members -
        //          typically a pointer to the text, a size & capacity etc..
        std::string::const_iterator j = rhs.my_string.begin();
        for (std::string::iterator i = my_string.begin(); i != my_string.end() && j != rhs.my_string.end(); ++i, ++j)
            *i ^= *j;

        // note: you'll have to decide what to do for different-length string data, doubles etc.
    }

この xor は、ポインターや double などのメンバーを無効にすることに注意してください。元の値を復元するために再度 xor しない限り、これらの型としてそれらを読み取ってはいけません。

于 2012-07-17T10:02:14.037 に答える