首页 > 解决方案 > 如何使用标准库函数返回两个值的函子?

问题描述

我想解决以下问题:我有一个方程组

   ax+by=c

   dx+ey=f

我读过一个教程,我们可以使用如下仿函数

bool isIdd(int i){
 return ((i%2)==1)
}

并且我们可以将这个函子与 find_if 函数一起使用。

我想问是否有可能两个从函子(例如元组)返回两个值,我们可以将它与 find_if STL 函数一起使用吗?

标签: c++

解决方案


可以从仿函数返回两个值(例如元组)

是的,它是,但你也需要适当的

operator bool()

据我了解,你想要这样的东西:

#include <utility>
#include <algorithm>
#include <iterator>
#include <functional>

struct Pair{

    bool b;
    uint32_t data;

    operator bool()const{
        return this->b;
    }

    const Pair & isIdd(uint32_t p){
        if (p == this-> data) this->b = true;
     return *this ;
    }

    Pair(bool b , uint32_t data){
        this-> b = b;
        this->data = data;
    }

};

int main(){
    using namespace std::placeholders;
    Pair p(0,0);
    std::vector<uint32_t> vct {2};
    auto it = vct.begin ();
    auto b = std::bind(&Pair::isIdd,_1,_2);
    std::find_if(vct.begin (),vct.end (),b(p,*it++ ));
}

但是这里的内容与作为方程解的任务集无关。如果这适合您并且您真的想find_if用作它,请将其转换为模板并以某种方式存储找到的数据。


推荐阅读