2013-02-22 74 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)