在结构矢量中搜索

时间:2014-04-04 09:46:19

标签: c++ search vector struct

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

struct person_t
{

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

    vector <person_t> myvector;

我已阅读myvector中的项目

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

1 个答案:

答案 0 :(得分:5)

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" )
);

或丑陋但适用于所有场合))

template< class T, class FieldType, FieldType T::*FieldPtr >
struct EqualBy
{
    EqualBy( const FieldType & value ) : m_fieldValue( value ) {}
    bool operator()( const T & r ) const {
        return m_fieldValue == r.*FieldPtr;
    }
    bool operator()( const T * p ) const {
        return m_fieldValue == p->*FieldPtr;
    }
private:
    const FieldType m_fieldValue;
};

// usage:
typedef EqualBy< person_t, std::string, & person_t::name > EqualByName;
typedef EqualBy< person_t, std::string, & person_t::id > EqualById;
unsigned int namesCount = std::count_if( myvector.begin(), myvector.end(),
    EqualByName( "Bill Gates" )
);
unsigned int idsCount = std::count_if( myvector.begin(), myvector.end(),
    EqualById( "123456" )
);