stl算法课堂

发布于 2024-07-17 14:05:33 字数 98 浏览 1 评论 0原文

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

Is there a way to use stl algorithms like find() and find_if() in a container of objects?
Ex.:With find() find the element whit name "abc" in a vector of class Alfhabetic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风透绣罗衣 2024-07-24 14:05:33

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

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"));

You can define a comparing predicate (functor). Here is a generic implementation:

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

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

private:
   const std::string toCompare_;
};

In a vector of Alphabetic elements

std::vector< Alphabetic> vect;

you can run a search like:

std::find_if( vect.begin(), vect.end(), AlphabeticNameComp( "abc"));
知足的幸福 2024-07-24 14:05:33

您可以为 Alfhabetic 类定义一个 operator==() ,它仅与数据成员 abc 匹配,

如下所示:

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

然后查找 >Alfhabetic 实例使用 abc 初始化为您想要的值。

You can define an operator==() for class Alfhabetic that matches only the data member abc

something like that:

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

and then finding an Alfhabetic instance initialized with abc as the value you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文