如何查找/删除具有特定参数的结构向量的元素

How to find/remove an element of vector of struct with specific parameter?

本文关键字:参数 结构 元素 向量 何查找 查找 删除      更新时间:2023-10-16

我有一个slotAndId结构体,它是这样声明的

typedef struct {      
    int slot;
    int id;
} slotAndId;

然后我有一个向量,它包含许多类型的 slotAndId 对象......

slotAndId object;
vector<slotAndId> ids;
for (int i = 0; i < 20; i++) {
    object.slot = i;
    object.id = i + 2000;   //random id as example, this will be generated by something else in reality.
    ids.push_back(object);
}

例如,如果我想查找向量中是否有一个插槽等于 20 的 slotAndId 对象,我将如何在 C++98 中做到这一点?然后,我如何能够从矢量中删除该特定的 slotAndId 对象?

这就是

std::find_if的用途。

bool HasSlot20(const slotAndId& item)
{
    return item.slot == 20;
}
int main()
{
    std::vector<slotAndId> ids = {..};
    std::vector<slotAndId>::const_iterator it = std::find_if(
       ids.begin(),
       ids.end(),
       HasSlot20
    );
}

我们需要额外的函数,因为 C++98 没有 lambda,但我们可以通过使用函子来使其更灵活:

struct HasSlot
{
   HasSlot(const int id) : m_id(id) {}
   bool operator()(const slotAndId& item)
   {
      return item.slot == m_id;
   }
private:
   const int m_id;
};
int main()
{
    std::vector<slotAndId> ids = {..};
    std::vector<slotAndId>::const_iterator it = std::find_if(
       ids.begin(),
       ids.end(),
       HasSlot(20)
    );
}

或:

int main()
{
    HasSlot finder(20);
    std::vector<slotAndId> ids = {..};
    std::vector<slotAndId>::const_iterator it = std::find_if(
       ids.begin(),
       ids.end(),
       finder
    );
}

现在,可以使用不同的参数重用此逻辑。

或者只是有一个循环!

如果您的容器非常大,则可以考虑使用不同的(或附加的(数据结构,该结构可以在比线性时间内更好地完成此操作。