2
有沒有辦法在對象的容器中使用find()和find_if()等stl算法?例如:find()在Alfhabetic類的向量中找到元素名稱「abc」。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
爲你想要的值初始化。