如何查找/删除具有特定参数的结构向量的元素
How to find/remove an element of vector of struct with specific parameter?
我有一个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
);
}
现在,可以使用不同的参数重用此逻辑。
或者只是有一个循环!
如果您的容器非常大,则可以考虑使用不同的(或附加的(数据结构,该结构可以在比线性时间内更好地完成此操作。
相关文章:
- 使用不带参数的函数访问结构元素
- 将结构字段的类型展开为可变模板参数
- MSVC将仅移动结构参数解释为指针
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 如何传递带有通过引用传递的结构参数的函数?
- 展开可变参数模板结构
- 在类构造函数中定义结构变量的参数
- 如何在方法中传递结构参数
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 带参数的数据结构的全局声明
- C++ 带有默认参数的结构,可选择在构造函数中更改
- C++-将具有引用的长参数列表重构为结构
- 为私有结构定义双参数运算符重载
- 我们可以用参数化构造函数初始化结构的数组吗?
- 关于类的想法 参数结构给定实现
- 重映射模板参数结构
- 从C 调用的编译MATLAB函数的输入参数结构
- 如何实现具有不同参数结构的纯虚拟函数
- 如何在C++中获得可更改的函数参数结构
- 函数参数 -> 结构体成员的 void* 和常量 void* 的解决方案