在下面的第一个代码片段中,我尝试根据输入 std::remove_if 函数的静态条件函数从成员函数内的 vector 中删除元素。我的问题是,removeVipAddress 方法中的输入参数 uuid 无法在条件函数内访问。您认为我应该在这里做什么才能根据名为 uuid 的输入参数从 vector 中删除项目?谢谢。注意:这是之前在 Removing an item from an std:: vector 中解释的后续问题
片段 1(代码)
void removeVipAddress(std::string &uuid)
{
struct RemoveCond
{
static bool condition(const VipAddressEntity & o)
{
return o.getUUID() == uuid;
}
};
std::vector<VipAddressEntity>::iterator last =
std::remove_if(
mVipAddressList.begin(),
mVipAddressList.end(),
RemoveCond::condition);
mVipAddressList.erase(last, mVipAddressList.end());
}
片段 2(编译输出)
$ g++ -g -c -std=c++11 -Wall Entity.hpp
Entity.hpp: In static member function ‘static bool ECLBCP::VipAddressSet::removeVipAddress(std::string&)::RemoveCond::condition(const ECLBCP::VipAddressEntity&)’:
Entity.hpp:203:32: error: use of parameter from containing function
Entity.hpp:197:7: error: ‘std::string& uuid’ declared here
最佳答案
如果您使用的是 C++11,这可以通过 lambda 来完成:
auto last = std::remove_if(
mVipAddressList.begin(),
mVipAddressList.end(),
[uuid]( const VipAddressEntity& o ){
return o.getUUID() == uuid;
});
该函数调用的最后一个参数声明了一个 lambda,它是一个匿名内联函数。 [uuid]
位告诉它在 lambda 范围内包含 uuid
。
有一个关于 lambda 的教程 here
或者,您可能希望为RemoveCond谓词提供构造函数和成员函数(并使用operator()而不是名为condition的函数来实现它)。
类似这样的事情:
struct RemoveCond
{
RemoveCond( const std::string& uuid ) :
m_uuid( uuid )
{
}
bool operator()(const VipAddressEntity & o)
{
return o.getUUID() == m_uuid;
}
const std::string& m_uuid;
};
std::remove_if(
mVipAddressList.begin(),
mVipAddressList.end(),
RemoveCond( uuid );
);
关于c++ - 后续:从 std::vector 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15025325/