使用 STL find

编程入门 行业动态 更新时间:2024-10-12 05:51:42
本文介绍了使用 STL find_if() 在对象指针向量中查找特定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在对象指针向量中查找某个对象.假设这些是我的课程.

I'm trying to find a certain object in a Vector of object pointers. Lets say these are my classes.

// Class.h class Class{ public: int x; Class(int xx); bool operator==(const Class &other) const; bool operator<(const Class &other) const; }; // Class.cpp #include "Class.h" Class::Class(int xx){ x = xx; } bool Class::operator==(const Class &other) const { return (this->x == other.x); } bool Class::operator<(const Class &other) const { return (this->x < other.x); } // Main.cpp #include <iostream> #include <vector> #include <algorithm> #include "Class.h" using namespace std; int main(){ vector<Class*> set; Class *c1 = new Class(55); Class *c2 = new Class(34); Class *c3 = new Class(67); set.push_back(c31); set.push_back(c32); set.push_back(c33); Class *c4 = new Class(34); }

可以说,就我的目的而言,如果它们的x"值相同,则类的 2 个对象是相等的.所以在上面的代码中,我想在 STL find_if() 方法中使用一个谓词,以便能够在向量中找到"c4.

Lets say that for my purposes, 2 objects of class are equal if their 'x' values are the same. So in the above code, i'd like to use a predicate in the STL find_if() method to be able to 'find' c4 in the vector.

我似乎无法让谓词起作用.我的 find 谓词基于我为排序而编写的谓词.

I can't seem to get a predicate to work. I'm basing my find predicate on the predicate I wrote for sorting.

struct less{ bool operator()(Class *c1, Class *c2){return *c1 < *c2;} }; sort(set.begin(), set.end(), less());

这个排序谓词工作正常.所以我调整了它以用于查找

This sorting predicate works fine. So I adapted it to use for finding

struct eq{ bool operator()(Class *c1, Class *c2){return *c1 == *c2;} };

为什么这个谓词不起作用?为此编写谓词的更好方法是什么?

Why won't this predicate work? What is the better way of writing a predicate for this?

谢谢

推荐答案

find_if 采用一元谓词,而不是二元谓词.

find_if takes a unary predicate, NOT a binary predicate.

struct eq{ eq(const Class* compare_to) : compare_to_(compare_to) { } bool operator()(Class *c1) const {return *c1 == *compare_to_;} private: const Class* compare_to_; };

std::find_if(set.begin(), set.end(), eq(c4));

更多推荐

使用 STL find

本文发布于:2023-11-30 14:39:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:STL   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!