【问题标题】:Using a algorithm for searching a string in a vector使用算法在向量中搜索字符串
【发布时间】:2015-11-05 23:05:30
【问题描述】:

是否可以使用算法方法计算多少个字符串等于作为参数给出的一个?

#include <algorithm>
#include <vector>
#include <string>
int main(){
    vector<string> vectorPeople;
    //assume that myVector isn't empty
    string name;
    cin >> name;
    int total=std::count(myVector.begin(),myVector.end(),name);

 }

【问题讨论】:

  • 使用vector&lt;string&gt;::iterator循环遍历向量中的每个字符串,并将字符串与参数一一比较
  • @willywonka_dailyblah 有一种方法。除了那个 op 明确要求算法 API 提供一个方法。
  • 我将此标记为“不清楚你在问什么”。这个问题已经有了答案;但它基本上包含与您在问题中的代码相同的代码;此外,问题似乎没有被编辑,所以我认为在编写答案时代码就在那里。由于我能理解您提出的唯一问题已在问题正文中得到解答,因此我无法想象您实际上在问什么。

标签: algorithm vector stl count


【解决方案1】:

是的。您可以使用std::count(您可以通过简单的搜索轻松找到)。

#include <vector>
#include <algorithm>
#include <string>

int count(std::vector<std::string> strings , std::string to_search){
    return std::count(strings.begin() , strings.end() , to_search);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多