Search code examples
c++arraysvectoriteratorstd

Counting matches in vector of structs


I have a problem that requires me to count the number of instances within this array that uses either std::count() or std::find(). I'm aware of how to do this using a standard data (see bottom code) type but not with the NameContainer that I'm using.

//Type
struct NameContainer{
    char name [32];
}

//An array of containers
NameContainer *_storedNames = new NameContainer[_numberOfNames];

//An example of what I'm trying to do with a string rather than the NameContainer
std::vector<string> v(_storedNames, _storedNames + _numberOfNames);
//returns an numeric value
return std::count(v.begin(), v.end(), nameToSearch))

Solution

  • You can use a functor

    struct names_equal {
        string comp_to;
    
        names_equal(string a) : comp_to(a) {}
    
        bool operator()(NameContainer& p) {
            return p.name == comp_to;
        }
    };
    

    And count like

    cout << std::count_if(v.begin(), v.end(), names_equal(nameToSearch));
    

    This way nameToSearch doesn't have to be hard coded.


    EDIT

    If you can not use count_if, and has to be count then modify NameContainer and overload == for it.

    struct NameContainer{
        string name;
    
        bool operator==(string str) {
            return name == str;
        }
    };
    

    Then count like this

    cout << std::count(v.begin(), v.end(), nameToSearch);