0

C ++でセットリストを作成し、要素でいっぱいにしました

std::set<Unit*> myUnits; 

for(std::set<Unit*>::iterator i = myUnits.begin(); i != myUnits.end(); i++) {   
    if() {}
}

だから、セットリストのすべての要素をチェックしたいのですが、何を入れる必要がありますか?

4

3 に答える 3

3

おそらく次のようなものが必要です。

(*i)->stringVal
于 2011-11-21T17:04:53.283 に答える
2

Unit* pUnit = *i;オブジェクトへのポインタを提供しUnitます。ちなみに、コンテナの正しい用語は「setlist」ではなく「set」です。

于 2011-11-21T17:03:44.207 に答える
1

あなたが何を望んでいるのか正確にはわかりませんが、Unitクラスにbool Unit::check()メソッドがあると仮定しましょう。次に、次のように書く必要があります。

if (i->check()) {...}

編集:申し訳ありませんが、一連のポインターがあることに気づきませんでした...セットはポインターアドレスを比較し、それらが等しいかどうかを定義するためにユニットのコンテンツを比較するため、それが実際に必要なものかどうかわかりません。Unit-objects と Unit-objects へのポインターを使用してセットを使用する方法を示す小さなコード サンプルを次に示します。

class Unit
{
public:
    Unit(unsigned int id, bool c)
    {
    this->id = id; // should be unique
    checked = c;
    }

    bool check() const
    {
    return checked;
    }

    unsigned int getId() const
    {
    return id;
    }

    bool operator<(const Unit &u) const // this is needed for the set<Unit>, otherwise two Units can't be compared
    {
    return this->id < u.id;
    }

private:
    bool checked;
    unsigned int id;
};

void setTest()
{
    set<Unit> myUnits;

    Unit u1(1,true);
    Unit u2(2,false);
    Unit u3(2,true);

    myUnits.insert(u1);
    myUnits.insert(u2);
    myUnits.insert(u3);

   cout << "set<Unit>:" << endl;
   for (std::set<Unit>::iterator it = myUnits.begin(); it != myUnits.end(); ++it)
   {
        if (it->check()) // you can access the Unit-object stored in the set like this...
        {
            cout << "Unit " << it->getId() << ": checked" << endl;
        }
        else
        {
                        // ... or like this
            Unit u = *it;
            cout << "Unit " << u.getId() << ": check failed" << endl;
        }
    }

    set<Unit*> myUnitPtrs;

    myUnitPtrs.insert(&u1);
    myUnitPtrs.insert(&u2);
    myUnitPtrs.insert(&u3);

    cout << "set<Unit*>:" << endl;
    for (std::set<Unit*>::iterator it = myUnitPtrs.begin(); it != myUnitPtrs.end(); ++it)
    {
        if ((*it)->check()) // you can access a Unit-Pointer like this ...
        {
            cout << "Unit " << (*it)->getId() << ": checked" << endl;
        }
        else
        {
            Unit *u = *it; // ... or like this
            cout << "Unit " << u->getId() << ": check failed" << endl;
        }
    }
}

出力は次のようになります。

set<Unit>:
Unit 1: checked
Unit 2: check failed // inserting u3 doesn't change the set as a Unit with id 2 is already present in the set
set<Unit*>:
Unit 1: checked
Unit 2: check failed
Unit 2: checked // now there's two Units with id 2, because u2 and u3 have different adresses
于 2011-11-21T17:07:43.770 に答える