如何在矢量中找到一些东西

时间:2011-11-18 18:20:04

标签: c++ stl vector

我有一个指向带建筑物的Vector的指针。

vector<building> * building1;
building1 = gamer.getBuilding(); ( building1 is a pointer to vector with all buildings that gamer has on that moment. )

现在我想检查是否在该向量中存在一个名为house的建筑物。

我以为我可以做点什么

vector<building>::iterator it;

it = find((*building1).begin(), (*building1).end(),buildings::house);

建筑物是一个枚举。

但这不起作用。

有人可以帮助我吗?

亲切的问候,

3 个答案:

答案 0 :(得分:3)

您可以使用std::find_if。它需要谓词作为第三个参数。因此,您可以编写函数或函数对象,并将其用作谓词。用法的语法是:

std::vector<building>::iterator it = std::find_if(v.begin(), 
                                                    v.end(), 
                                                    predicate);

在C ++ 11中,您可以直接使用lambda:

auto it = std::find_if(v.begin(), v.end(), 
                           [](const building & b)
                           {
                               //your code: which object you want to find?
                               //for example
                               return b.Name == "GhostBuilding";
                           });

请注意auto的用法。

答案 1 :(得分:3)

答案取决于您未展示的building的定义。但一般来说,当你不想按价值找到但通过谓词找到时,你会使用find_if

struct building_of_type
{
public:
    explicit building_of_type( buildings type ) : _type( type ){}

    bool operator ()( building const& b ) const {  return is b of type _type?; }
private:
    buildings const _type;
};

std::find_if(
    building1->begin(), building1->end()
  , building_of_type( buildings::house )
);

或更简单的案例:

bool is_building_a_house( building const& b ){ return is b of type house?; }

std::find_if(
    building1->begin(), building1->end()
  , is_building_a_house
);

答案 2 :(得分:0)

您可以std::find_if使用binary_function

struct BuildingExistsPredicate : public std::binary_function<BuildingType, std::string, bool> {
    bool operator()(const BuildingType& building, const std::string& name) const {
        return building.name == name;
    }
};

然后

vector<BuildingType> *building1 = gamer.getBuilding();
vector<BuildingType>::iterator it = std::find_if(building1->begin(), building1->end(), std::bind2nd(BuildingExistsPredicate(), "house"));

if(it == building1->end()) {
    std::cerr << "Building not found\n";
    return;
}

// it now points to the first building whose name is "house"

如果找到该项目,it将指向该项目。否则,it将指向building1->end()

相关问题