后续操作:从std::向量中删除一个项目
Follow-up: Removing an item from an std:: vector
在下面的第一个代码片段中,我试图基于std::remove_if函数中的静态条件函数,从成员函数内的向量中删除一个元素。我的问题是removeVipAddress方法中的输入参数uuid无法在条件函数中访问。您认为我应该在这里做些什么来实现基于名为uuid的输入参数从向量中删除项目?谢谢注意:这是前面在从std::vector 中删除项目中解释的后续问题
SNIPET 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());
}
SNIPET 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]
比特告诉它将uuid
包括在lambda的范围中。
这里有一个关于lambdas的教程
或者,您可能希望提供一个构造函数&RemoveCond谓词的成员函数(并使用运算符()而不是名为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++11 lambdas,您可以将RemoveCond
表示为函子:
struct RemoveCond
{
RemoveCond(const std::string uuid) : uuid_(uuid) {}
bool operator()(const VipAddressEntity & o) const
{
return o.getUUID() == uuid_;
}
const std::string& uuid_;
};
然后将实例传递给std::remove_if
:
std::remove_if(mVipAddressList.begin(),
mVipAddressList.end(),
RemoveCond(uuid));
BTW您的removeVipAddress
函数应该采用const
参考:
void removeVipAddress(const std::string &uuid)
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 从链接列表c++中删除一个项目
- 删除映射和分割错误中的一个过去结束元素
- 使用另一个字符串从字符串中删除空格
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 如何知道地图中的最后一个元素是否被删除?
- G++ 发出警告,要求删除一个代码的数组,但不删除另一个代码的数组
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 如何删除矢量中的重复值,最后一个除外
- C++ 删除存在于另一个矢量中的矢量项,同时保留顺序
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- 删除链接列表中剩余的最后一个节点
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 在C++中为二叉搜索树创建一个删除函数
- 当编译一个删除停止字并应用大小写折叠的程序时,会出现一个奇怪的代码
- 为什么C++仍然有一个删除[]和一个删除运算符
- 一个删除行的函数