Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在结构向量中搜索_C++_Search_Vector_Struct - Fatal编程技术网

C++ 在结构向量中搜索

C++ 在结构向量中搜索,c++,search,vector,struct,C++,Search,Vector,Struct,我有一个充满结构的向量,看起来像这样 struct person_t { string name; string id; struct location_t location; }; vector <person_t> myvector; struct person\t { 字符串名; 字符串id; 结构位置\u t位置; }; 向量myvector; 我已经阅读了myvector中的项目 但现在我需要知道如何搜索向量中的特定项,并计算

我有一个充满结构的向量,看起来像这样

struct person_t
{

    string name;
    string id;
    struct location_t location;    
};

    vector <person_t> myvector;
struct person\t
{
字符串名;
字符串id;
结构位置\u t位置;
};
向量myvector;
我已经阅读了myvector中的项目

但现在我需要知道如何搜索向量中的特定项,并计算向量中该项的数量

unsigned int count = std::count_if( myvector.begin(), myvector.begin(),
    []( const person_t & p ) { return p.name == "Bill Gates"; }
);
或者没有c++11

struct EqualByName {
    EqualByName( const std::string & name ) : m_name( name ) {}
    bool operator()( const person_t & p ) const { return p.name == m_name; }
private:
    std::string m_name;
};
unsigned int count = std::count_if( myvector.begin(), myvector.begin(),
    EqualByName( "Bill Gates" )
);
或丑陋,但在所有场合都适用)

模板
结构等式
{
EqualBy(const FieldType&value):m_fieldValue(value){}
布尔运算符()(常数T&r)常数{
返回m_fieldValue==r.*FieldPtr;
}
布尔运算符()(常数T*p)常数{
返回m_fieldValue==p->*FieldPtr;
}
私人:
常量字段类型m_字段值;
};
//用法:
typedef EqualByEqualByName;
typedef EqualByEqualById;
unsigned int namesCount=std::count_if(myvector.begin(),myvector.end(),
EqualByName(“比尔·盖茨”)
);
unsigned int idsCount=std::count_if(myvector.begin(),myvector.end(),
EqualById(“123456”)
);
或者没有c++11

struct EqualByName {
    EqualByName( const std::string & name ) : m_name( name ) {}
    bool operator()( const person_t & p ) const { return p.name == m_name; }
private:
    std::string m_name;
};
unsigned int count = std::count_if( myvector.begin(), myvector.begin(),
    EqualByName( "Bill Gates" )
);
或丑陋,但在所有场合都适用)

模板
结构等式
{
EqualBy(const FieldType&value):m_fieldValue(value){}
布尔运算符()(常数T&r)常数{
返回m_fieldValue==r.*FieldPtr;
}
布尔运算符()(常数T*p)常数{
返回m_fieldValue==p->*FieldPtr;
}
私人:
常量字段类型m_字段值;
};
//用法:
typedef EqualByEqualByName;
typedef EqualByEqualById;
unsigned int namesCount=std::count_if(myvector.begin(),myvector.end(),
EqualByName(“比尔·盖茨”)
);
unsigned int idsCount=std::count_if(myvector.begin(),myvector.end(),
EqualById(“123456”)
);