我在 C++ 中创建了一个集合列表并充满了元素
std::set<Unit*> myUnits;
for(std::set<Unit*>::iterator i = myUnits.begin(); i != myUnits.end(); i++) {
if() {}
}
所以我想在 if 中检查 setlist 的每个元素,如果必须放入什么?
你可能想要这样的东西:
(*i)->stringVal
Unit* pUnit = *i;
会给你一个指向Unit
对象的指针。顺便说一句,容器的正确术语是“set”,而不是“setlist”。
我不确切地知道你想要什么,但让我们假设,这个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