2013-02-22 75 views
2

在下面的第一个代码片段中,我试图从一个成员函数中的一个向量中移除一个元素,该元素基于一个静态条件函数馈入std :: remove_if函数。我的问题在于,在条件函数中无法访问removeVipAddress方法中的输入参数uuid。基于名为uuid的输入参数,您认为我应该在这里执行什么操作以从矢量中移除项目?谢谢。注:这是一个后续问题Removing an item from an std:: vector先前解释后续行动:从std :: vector中删除一个项目

SNIPPET 1(CODE)

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 

回答

2

如果您在使用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谓词(使用操作符()而不是函数名称的条件实现它)。

事情是这样的:

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); 
    ); 
1

如果你没有C++ 11个lambda表达式,你可以表达你的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)); 

顺便说一下你removeVipAddress函数应该采取const参考:

void removeVipAddress(const std::string &uuid)