stl类中的算法

问题描述:

有没有办法在对象的容器中使用find()和find_if()等stl算法?例如:find()在Alfhabetic类的向量中找到元素名称“abc”。stl类中的算法

您可以定义一个比较谓词(函子)。这里是一个通用的实现:

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

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

private: 
    const std::string toCompare_; 
}; 

按字母元素

的矢量
std::vector< Alphabetic> vect; 

可以运行像搜索:

std::find_if(vect.begin(), vect.end(), AlphabeticNameComp("abc")); 

您可以定义Alfhabetic类匹配的operator==()只有数据成员abc

类似的东西:

bool operator==(const Alfhabetic& a, const Alfhabetic& b) 
{ 
    return (a.abc == b.abc); 
} 

,然后找到一个Alfhabetic实例与abc为你想要的值初始化。