1

ここで質問を簡単にしようとしています。メンバー変数として int 配列を持つ構造体が 1 つあります。

struct elem
{
    elem (int a, int b, int c) {id[0]=a; id[1]=b; id[2]=c;}
    int id[3];
};

elem ポインターを std::set に入れたいのですが、後で find() を使用してそのセットから特定のオブジェクトを検索したいので、この std::set にカスタム コンパレーターを提供したいと考えています。

struct compare
{
    bool operator() (elem *one, elem *two )
    {
            // logic 
    }
};

int main(int argc, char* argv[])
{
    std::set< elem *, compare> elemSet;
    std::set< elem *, compare>::iterator itr;

    elem ob1(2,5,9), ob2(5,9,7), ob3(4,3,7);

    elemSet.insert(&ob1);
    elemSet.insert(&ob2);
    elemSet.insert(&ob3);

    elem temp(4,3,7);
    itr = elemSet.find(&temp);

    if(itr != elemSet.end())
    {
        cout << endl << (*itr)->id[0] << " " << (*itr)->id[1] << " " << (*itr)->id[2]; 
    }

    return 0;
}

コンパレータのロジックを教えてください。任意のサイズの配列の一般的なロジックはありますか?

4

1 に答える 1

2

std::set(およびstd::mapそのmultiバリアント) はstrict-weak 順序付けを必要とするため、コンパレータを介してその順序付けを提供する必要があります。厳密弱順序付けは、

(x < x) == false
(x < y) == !(y < x)
((x < y) && (y < z)) == (x < z)

これは、多くのメンバーを持つクラスの実装が複雑になる可能性があります (必要に応じて、配列は単なるメンバーのコレクションです)。

私のこの質問ではtuple、とを介して厳密弱順序付けを実装することが賢明かどうかを尋ねましたtie。これにより、途方もなく簡単になります。

struct compare
{
    bool operator() (elem const* one, elem const* two )
    {   // take 'tie' either from Boost or recent stdlibs
        return tie(one->id[0], one->id[1], one->id[2]) <
               tie(two->id[0], two->id[1], two->id[2]);
    }
};

また、引数を pointers-to- として取っていることにも注意してくださいconst

于 2011-11-29T09:22:09.843 に答える