后续操作:从std::向量中删除一个项目

Follow-up: Removing an item from an std:: vector

本文关键字:一个 删除 项目 操作 std 向量      更新时间:2023-10-16

在下面的第一个代码片段中,我试图基于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)