【问题标题】:Find element of vector of speciefic objects by 2 fields [duplicate]通过2个字段查找特定对象的向量元素[重复]
【发布时间】:2014-11-30 14:06:06
【问题描述】:

我有一个 S 班:

class S
{
public:
    S(int ssx, int ssy, int cnt)
    {
        sx = ssx;
        sy = ssy;
        count = cnt;
    }
    int sx;
    int sy;
    int count;
};

我想创建一个容器,它可以找到与 2 个参数匹配的元素的指针(迭代器)(如对 {sx, sy},这对应该等于容器中元素的对)。 是否有任何 STL 方法或者我应该使用圆 FOR(;;) 和 S* 的简单向量来实现搜索?

【问题讨论】:

    标签: c++ stl containers


    【解决方案1】:

    你可以使用std::find_if()

    首先,为两个成员声明一个谓词类

    struct CmpS {
        int x;
        int y;
        CmpS(int x, int y) { this.x = x; this.y = y; }
        bool operator()(const S& s) const { return s.sx == x && s.sy == y; }
    };
    

    然后,拨打std::find_if()

    std::vector<S> vec;
    std::vector<S>::iterator iter = std::find_if(vec.begin(), vec.end(), CmpS(x, y));
    

    【讨论】:

    • 谓词可能是 C++11 的 lambda。
    猜你喜欢
    • 2020-06-24
    • 2017-05-10
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多