我想找到与我在 std::vector 中寻找的字符串相似的字符串,如下所示:
int main() {
std::vector<std::string> v;
v.push_back("hellostr");
v.push_back("thisishello");
v.push_back("x!");
std::cout << std::count(v.begin(), v.end(), "hello") << std::endl;
return 0;
}
$ ./prog
2
您可以使用
count_if()
和 find()
:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
static const bool _find(const std::string &s, const std::string &sub)
{
return s.find(sub) != std::string::npos;
}
int main()
{
std::vector<std::string> v = {"hellostr", "thisishello", "x!"};
std::string similar = "hello";
int c = std::count_if(v.begin(), v.end(), [&similar](const std::string &s)
{ return _find(s, similar); });
std::cout << c << "\n";
return 0;
}
2