class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
//设置可以获得ruleKey在items中的下标的哈希表
unordered_map<string, int> dictionary = { {"type", 0}, {"color", 1}, {"name", 2} };
//获得rulekey下标,例如ruleKe=color,则index=1
int res = 0, index = dictionary[ruleKey];
//万能引用左右值都可以引用
for (auto&& item : items) {
//比较ruleKey下标元素是否和ruleValue相同,相同则将总值加一
if (item[index] == ruleValue) {
res++;
}
}
return res;
}
};
首先用哈希表来判断ruleKey在数组中的下标位置,再利用循环对相应的下标的值与ruleValue比较,如果相同则结果值加一。