c++ - 后续:从 std::vector 中删除项目

标签 c++ stdvector

在下面的第一个代码片段中,我尝试根据输入 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/

相关文章:

c++ - Memcpy 数据直接存入 std::vector

c++ - 使用 std::map 而不是 vector<pair<string, string>> 我会看到性能提升吗?

c++ - 访问 vector vector 元素时出现段错误

c++ - 快速整数矩阵乘法与 bit-twiddling hacks

c++ - 为什么 Sleep(500) 花费超过 500 毫秒?

c++ - basic_string::_S_construct null 无效 - 不明白为什么?

c++ - 如何使用STL算法将整数 vector 转换为字符串 vector ?

c++ - 在头文件中声明结构体 C++

c++ - 教程c++引用参数问题

c++ - 将 vector 的 vector 的第二维设置为零 (C++)