类中的stl算法

Hai*_*Hai 2 c++ stl

有没有办法在对象容器中使用像find()和find_if()这样的stl算法?例如:使用find()在类Alfhabetic的向量中找到元素名称"abc".

Căt*_*tiș 7

您可以定义比较谓词(仿函数).这是一个通用的实现:

struct AlphabeticNameComp
{
   AlphabeticNameComp( const std::string& toCompare)
      : toCompare_( toCompare) { }

   bool operator()( const Alphabetic& obj) const
   {
       return toCompare_ == obj.name();
   }

private:
   const std::string toCompare_;
};
Run Code Online (Sandbox Code Playgroud)

在字母元素的向量中

std::vector< Alphabetic> vect;
Run Code Online (Sandbox Code Playgroud)

你可以运行像这样的搜索:

std::find_if( vect.begin(), vect.end(), AlphabeticNameComp( "abc"));
Run Code Online (Sandbox Code Playgroud)