STL:为向量写“where”运算符

时间:2010-06-08 17:03:13

标签: c++ stl vector

我需要根据几个布尔谓词在向量中找到索引。

前:

vector<float> v;
vector<int> idx;

idx=where( bool_func1(v), bool_func2(v), ... );

声明**where**函数的方法是什么,为了在向量上使用几个用户定义的布尔函数?

感谢 阿尔曼。

一周后修改

我用模板做了一些复杂的解决方案。但实际上,我可以使用已经预定义的valarray来完成我的任务。以下是可能会发现它有用的代码片段:

  double dr=Rc/(double)Nbins, r;
  sigma.resize(Nbins);
  rr=sigma;
  valarray<double> vz(&data.vz[0], data.vz.size());
  double mvel=vz.sum()/(double)vz.size();
  for(size_t i=0l;i<Nbins;i++)
   {
   r=dr*i;
   valarray<bool> ids = (dist < r+dr) && (dist > r);//The magic valarray<bool>
   if(ids.max())
    {
    valarray<double> d=vz[ids];//we can use indirect operation.
    d-=mvel;
    d=pow(d,2.0);
    sigma[i]= sqrt(d.sum()/(double)d.size());
    rr[i]=r;
    cout<<i<<") "<<r<<" "<<sigma[i]<<endl;
    }
   }

5 个答案:

答案 0 :(得分:10)

使你的bool_xxx函数实际上是特定类型的函子(标签调度就足够了)。然后覆盖||和&amp;&amp;对于他们来说这些运算符返回bool_and或bool_or。然后你可以使用你的bool_谓词:


std::find_if(vect.begin(), vect.end(), bool_x1() || bool_x2() && (bool_x3() || bool_x4() && bool_x5()));

如果您想写一个“where”函数,那么您显然希望使用一组不同的bool_xxx函数执行此操作。即使你现在知道你想要某种类型的作品,你也可以尽可能地使它成为通用的。我就是这样做的。

编辑:

基于此评论: @Jerry:例如,我需要知道:id = where(v&lt; 10.0&amp;&amp; v&gt; 1.0);以后我想知道:id = where(v&lt; fun(v)); 使用boost :: lambda可能会更好:


namespace l = boost::lambda;
std::find_if(vect.begin(), vect.end(), l::_1 < 10.0 && l::_1 > 1.0);
std::find_if(vect.begin(), vect.end(), l::_1 < l::bind(fun, l::_1));

或者,如果你讨厌lambda或者不允许使用它......或者只是想要一个非常好的语法(但无法直接使用函数),那么只需创建自己的占位符类型并覆盖它以返回bool_xxx仿函数在运营商&lt;,&gt;等等...

Edit2:这是一个未经测试的地方,它向所有匹配的对象返回一个迭代器向量:


template < typename ForwardIter, typename Predicate >
std::vector<ForwardIter> where(ForwardIter beg, ForwardIter end, Predicate pred)
{
  ForwardIter fit = std::find_if(beg,end,pred);
  if (fit == end) return std::vector<ForwardIter>();

  ForwardIter nit = fit; ++nit;
  std::vector<ForwardIter> collection = where(nit,end,pred);
  collection.push_front(fit);
  return collection;
}

它是递归的,在某些实现上可能会很慢,但有一种方法可以做到。

答案 1 :(得分:3)

您可以使用transform的谓词版本(如果有的话)。没有一个,但写起来很容易:

template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first, 
                            InputIterator last, 
                            OutputIterator result, 
                            UnaryFunction f, 
                            Predicate pred)
{
    for (; first != last; ++first)
    {
        if( pred(*first) )
            *result++ = f(*first);
    }
    return result; 
}

然后你需要一种方法来组合多个谓词,这样你就可以表达像find_if( begin, end, condition1 && condition2 )这样的东西。再次,这很容易写:

template<typename LHS, typename RHS> struct binary_composite : public std::unary_function<Gizmo, bool>
{
    binary_composite(const LHS& lhs, const RHS& rhs) : lhs_(&lhs), rhs_(&rhs) {};

    bool operator()(const Gizmo& g) const
    {
        return lhs_->operator()(g) && rhs_->operator()(g);
    }
private:
    const LHS* lhs_;
    const RHS* rhs_;
};

最后,您需要一个transform_if用于将对象引用转换为对象指针的Gizmo。惊喜,惊喜,易写...

template<typename Obj>  struct get_ptr : public std::unary_function<Obj, Obj*>
{
    Obj* operator()(Obj& rhs) const { return &rhs; }
};

让我们用一个具体的例子来说明这一切。下面的Gizmo是您拥有的对象。我们有2个谓词find_letterfind_value,我们要在主vector中搜索匹配项。 transform_iftransform的谓词版本,get_ptr将对象引用转换为指针,binary_composite将两个复合词串在一起。

#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
using namespace std;

struct Gizmo
{
    string name_;
    int value_;
};

struct find_letter : public std::unary_function<Gizmo, bool>
{
    find_letter(char c) : c_(c) {}
    bool operator()(const Gizmo& rhs) const { return rhs.name_[0] == c_; }
private:
    char c_;
};

struct find_value : public std::unary_function<Gizmo, int>
{
    find_value(int v) : v_(v) {};
    bool operator()(const Gizmo& rhs) const { return rhs.value_ == v_; }
private:
    int v_;
};

template<typename LHS, typename RHS> struct binary_composite : public std::unary_function<Gizmo, bool>
{
    binary_composite(const LHS& lhs, const RHS& rhs) : lhs_(&lhs), rhs_(&rhs) {};

    bool operator()(const Gizmo& g) const
    {
        return lhs_->operator()(g) && rhs_->operator()(g);
    }
private:
    const LHS* lhs_;
    const RHS* rhs_;
};

template<typename LHS, typename RHS> binary_composite<LHS,RHS> make_binary_composite(const LHS& lhs, const RHS& rhs)
{
    return binary_composite<LHS, RHS>(lhs, rhs);
}


template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first, 
                            InputIterator last, 
                            OutputIterator result, 
                            UnaryFunction f, 
                            Predicate pred)
{
    for (; first != last; ++first)
    {
        if( pred(*first) )
            *result++ = f(*first);
    }
    return result; 
}

template<typename Obj>  struct get_ptr : public std::unary_function<Obj, Obj*>
{
    Obj* operator()(Obj& rhs) const { return &rhs; }
};


int main()
{   
    typedef vector<Gizmo> Gizmos;
    Gizmos gizmos;
    // ... fill the gizmo vector

    typedef vector<Gizmo*> Found;
    Found found;
    transform_if(gizmos.begin(), gizmos.end(), back_inserter(found), get_ptr<Gizmo>(), binary_composite<find_value,find_letter>(find_value(42), find_letter('a')));

    return 0;

}

编辑:

基于sbi's iterative approach,这里是copy的谓词版本,它更符合一般的STL范例,并且可以与back_insert_iterator一起使用来完成本案例中所需的操作。它将为您提供vector对象,而不是迭代器或索引,因此我在上面发布的transform_if对于此用途仍然比copy_if更好。但这是......

template<class InputIterator, class OutputIterator, class Predicate>
OutputIterator copy_if(InputIterator first, 
                       InputIterator last, 
                       OutputIterator result, 
                       Predicate pred)
{
    for (; first != last; ++first)
    {
        if( pred(*first) )
            *result++ = *first;
    }
    return result;
}

答案 2 :(得分:1)

这似乎是一个问题,可以更容易解决像Prolog这样的声明性语言。无论如何我用C ++试了一下:

typedef float type;
typedef bool (*check)(type);

std::vector<int> where(const std::vector<type>& vec,
                       const std::vector<check>& checks)
{
    std::vector<int> ret;

    for (int i = 0; i < vec.size(); i++)
    {
        bool allGood = true;

        for (int j = 0; j < checks.size(); j++)
        {
            if (!checks[j](vec[i]))
            {
                allGood = false;
                break;
            }
        }

        if (allGood)
            ret.push_back(i);
    }

    return ret;
}

答案 3 :(得分:0)

我不确定您想要哪些索引。这是你想要实现的目标:

//Function pointer declaration
typedef bool (*Predicate)(const std::vector<float>& v);

//Predicates
bool bool_func1(const std::vector<float>& v)
{
    //Implement
    return true;
}

bool bool_func2(const std::vector<float>& v)
{
    //Implement
    return true;
}


std::vector<int> where_func(const std::vector<float>& v,
                const std::vector<Predicate>& preds)
{
    std::vector<int>  idxs;
    std::vector<Predicate>::const_iterator iter = preds.begin();
    std::vector<Predicate>::const_iterator eiter = preds.end();
    for(; iter != eiter; ++iter)
    {
        if((*iter)(v))
        {
            idxs.push_back(eiter - iter);
        }   
    }

    return idxs;
}

答案 4 :(得分:0)

template<typename Vector, typename T> std::vector<int> where(const std::vector<Vector>& vec, T t) {
    std::vector<int> results;
    for(int i = 0; i < vec.size(); i++) {
        if (t(vec[i])
            results.push_back(i)
    }
    return results;
}

根据需要重载其他函数对象参数。使用:

template<typename T> struct AlwaysAccept {
    bool operator()(const T& t) { return true; }
};
std::vector<float> floats;
// insert values into floats here
std::vector<int> results = where(floats, AlwaysAccept<float>());

诺亚罗伯特的解决方案很好,但我并不完全确定如何才能做到这一点。

相关问题