搜索结构向量的向量成员

时间:2015-01-06 09:11:45

标签: c++ boost

我有这样的结构:

enum crdType { CARTESIAN =0, SPHERICAL, CUSTOM1, CUSTOM2, .......};

struct customCRD {
   std::vector<coordinate> Corners;
   crdType type;
};

然后我定义了一个矢量&lt; customCRD&gt;,我们称之为vec_customCRD。

我想检查我的坐标是否在此向量内。 我能够检查特定类型是否可用:

vector < customCRD >::iterator iter = std::find_if(vec_customCRD.begin(), vec_customCRD.end(), boost::bind(&customCRD::type, _1) == CUSTOM1);

它是一种搜索坐标,这里,在矢量矢量内。

任何聪明的方式?

修改 我忘了提到我不能使用C ++ 11。并提升版本高于1.56

我想做以下代码:

coordinate a;  // coordinate is a class of coordinates
std::vector<coordinate> vecCrd;
vector < coordinate >::iterator Corditer;
for(vector < customCRD >::iterator iter  = vec_customCRD.begin(); iter  != vec_customCRD.end();iter++)
{
  vecCrd = iter->Corners;
  Corditer = std::find(vecCrd.begin(), vecCrd.end(), a);
  if(Corditer != vecCrd.end())
  { 
    std::cout << "yes, this is what I want" << std::endl;
    break;
  }
}  

1 个答案:

答案 0 :(得分:2)

如果你想使用Boost Range,你可以编写像

这样的东西
int main() {
    std::vector<customCRD> const v;

    std::cout << "{9,10} found: " << !boost::empty(v | filtered(customCRD::havingCorner(coordinate(9,10)))) << "\n";
    std::cout << "{3,5}  found: " << !boost::empty(v | filtered(customCRD::havingCorner(coordinate(3, 5)))) << "\n";
};

将谓词定义为:

struct customCRD {
    std::vector<coordinate> Corners;
    crdType type;

    struct havingCorner {
        coordinate _a;
        havingCorner(coordinate a) : _a(a) {}
        bool operator()(customCRD const& cc) const { return cc.Corners.end()!=std::find(cc.Corners.begin(), cc.Corners.end(), _a); }
    };
};

查看 Live On Coliru (带有数据的c ++ 11)

查看 Live On Coliru (c ++ 03)

#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>

using namespace boost::adaptors;

#include <iostream>

enum crdType { CARTESIAN =0, SPHERICAL, CUSTOM1, CUSTOM2 };

typedef std::pair<int,int> coordinate;

struct customCRD {
    std::vector<coordinate> Corners;
    crdType type;

    struct havingCorner {
        coordinate _a;
        havingCorner(coordinate a) : _a(a) {}
        bool operator()(customCRD const& cc) const { return cc.Corners.end()!=std::find(cc.Corners.begin(), cc.Corners.end(), _a); }
    };
};

int main() {
    std::vector<customCRD> const v { 
        customCRD { {  {1,  2},  {3,  4},  {5,  6} }, CARTESIAN },
        customCRD { {  {7,  8},  {9, 10}, {11, 12} }, SPHERICAL },
        customCRD { { {13, 14}, {15, 16}, {17, 18} },   CUSTOM2 },
    };

    std::cout << "{9,10} found: " << std::boolalpha << !boost::empty(v | filtered(customCRD::havingCorner(coordinate(9,10)))) << "\n";
    std::cout << "{3,5}  found: " << std::boolalpha << !boost::empty(v | filtered(customCRD::havingCorner(coordinate(3, 5)))) << "\n";
}