计算结构向量中的匹配。 [英] Counting matches in vector of structs.
本文介绍了计算结构向量中的匹配。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,需要我计算这个数组中使用std :: count()或std :: find()的实例数。我知道如何使用标准数据(参见底部代码)类型,但不知道我正在使用的NameContainer。
I have a problem that requires me to count the number of instances within this array that uses either the 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屋!
查看全文