在 std::vector 中查找相似字符串<std::string>

问题描述 投票:0回答:1

我想找到与我在 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
c++ algorithm find stdvector stdstring
1个回答
0
投票

您可以使用

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
© www.soinside.com 2019 - 2024. All rights reserved.