计算结构向量中的匹配项 [英] Counting matches in vector of structs

查看:64
本文介绍了计算结构向量中的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,要求我计算使用std::count()std::find()的数组中实例的数量.我知道如何使用标准数据(请参见底部代码)类型来执行此操作,但不能使用我正在使用的NameContainer.

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

推荐答案

您可以使用函子

struct names_equal {
    string comp_to;

    names_equal(string a) : comp_to(a) {}

    bool operator()(NameContainer& p) {
        return p.name == comp_to;
    }
};

计数就像

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

这种方式nameToSearch不必硬编码.

编辑

如果不能使用count_if,并且必须为count,则修改NameContainer并为其重载==.

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;
    }
};

然后像这样计数

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

这篇关于计算结构向量中的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆