Finding index of custom element in vector

Hi

I have a vector of objects of class Person(id,name) and i wanna know is there a way to find a person index in vector by its id and name? Is there a way to do it with overloading == operator in class Person?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

struct person
{
    int id = 0 ;
    std::string name ;

    // equal if both name and id match
    // you may want to make the name comparison case-insensitive
    friend bool operator== ( const person& a, const person& b )
    { return a.id == b.id && a.name == b.name ; }

    friend bool operator!= ( const person& a, const person& b )
    { return !(a==b) ; }
};

int main()
{
    const std::vector<person> people { { 26, "Athos" }, { 12, "Porthos" }, { 19, "Aramis" } } ;

    // find by both id and name
    // http://en.cppreference.com/w/cpp/algorithm/find
    const auto iter = std::find( std::begin(people), std::end(people), person{ 12, "Porthos" } ) ;
    if( iter != std::end(people) ) std::cout << "{ 19, \"Aramis\" } found at position " << iter - std::begin(people) << '\n' ;

    // find by id
    const int id = 19 ;
    const auto iter2 = std::find_if( std::begin(people), std::end(people),
                                    [id]( const person& p ) { return p.id == id ; } ) ;
                                    // http://www.stroustrup.com/C++11FAQ.html#lambda
    if( iter != std::end(people) ) std::cout << "id " << id << " found at position " << iter2 - std::begin(people) << '\n' ;

    // find by name
    const std::string name = "Athos" ;
    const auto iter3 = std::find_if( std::begin(people), std::end(people),
                                    [&name]( const person& p ) { return p.name == name ; } ) ;
    if( iter != std::end(people) ) std::cout << "name '" << name << "' found at position " << iter3 - std::begin(people) << '\n' ;
}

http://coliru.stacked-crooked.com/a/51062810915c83c2
Registered users can post here. Sign in or register to post.