繁体   English   中英

搜索结构向量

[英]Search in a vector of structs

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

struct person_t
{

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

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

或看上去很丑,但在所有情况下都可以))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM