我有一个字符串向量,我想要计算向量中的所有'Ace'.现在我只能找到一个......
int main()
{
std::vector<string> vec;
vec.push_back("Ace of Spades");
vec.push_back("Ace");
string value = "Ace";
int cnt = 0;
auto iter = find_if(begin(vec), end(vec), [&](const string &str)
{
return str.find(value) != str.npos;
});
if(iter == end(vec))
cout << "no found" << endl;
else
{
cout << *iter << endl;
cnt++;
cout << cnt++ << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用std::count_if:
auto cnt = count_if(begin(vec),
end(vec),
[&](const string& str) {
return str.find(value) != std::string::npos;
});
Run Code Online (Sandbox Code Playgroud)
请注意,这仅计算包含的字符串数"Ace",而不"Ace"计算向量元素中出现的总数.