[英]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.