Nar*_*ren 1 c++ algorithm iterator stl vector
我有以下代码:我在删除函数中遇到编译错误。我想从向量中删除元素与xinput 的值匹配的元素x。
class A
{
int x,y;
public:
init(int a, int b)
{
x = a; y= b;
}
int getX(){return x;}
}
class B
{
public:
void add (int a, int b)
{
A a1;
a1.init(a,b);
MyVector.push_back(a1);
}
void remove(int x)
{
MyVector.erase(remove_if(MyVector.begin(), MyVector.end(),
[&vec](int x){return (vec.getX() == x);}), MyVector.end());
}
vector<A> MyVector;
}
Run Code Online (Sandbox Code Playgroud)
你必须给一个返回类型,init(int a, int b)并且你;在类定义之后错过了两个s 并且使用std::remove_if()不正确。这是它的文档
#include <vector>
#include <algorithm>
class A
{
int x,y;
public:
void init(int a, int b)
{
x = a; y= b;
}
int getX(){return x;}
};
class B
{
public:
void add (int a, int b)
{
A a1;
a1.init(a,b);
MyVector.push_back(a1);
}
void remove(int x)
{
MyVector.erase(std::remove_if(MyVector.begin(), MyVector.end(),
[&x](auto & el){return (el.getX() == x);}), MyVector.end());
}
std::vector<A> MyVector;
};
Run Code Online (Sandbox Code Playgroud)
请注意auto & el == A & el。std::remove_if迭代向量并将其元素传递给 lambda,因此 lambda 参数类型应该与向量相同。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |