user3086529
user3086529

Reputation: 11

Search in a vector of structs

I have a vector full with structs look like this

struct person_t
{

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

    vector <person_t> myvector;

and i have read in the items in myvector

but now i need to know how to search for specific item in vector and count how many of that item it is in the vector.

Upvotes: 0

Views: 188

Answers (1)

borisbn
borisbn

Reputation: 5054

unsigned int count = std::count_if( myvector.begin(), myvector.begin(),
    []( const person_t & p ) { return p.name == "Bill Gates"; }
);

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

or ugly looking but for all occasions ))

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

Upvotes: 5

Related Questions