计算字符串向量中字符串的出现次数

count number of occurrences of a string in a vector of string

本文关键字:字符串 向量 计算      更新时间:2023-10-16

我的要求是计算字符串向量中字符串的出现次数。要搜索的字符串位于向量的第 0 个索引处。

我正在使用algorithm标头中的内置count函数,但遇到了一个奇怪的编译错误,我无法解决。

我的代码:

vector<string> a={"abc", "def", "abc"};
int cnt = count(a.begin(), a.end(), a[0]);

编译错误消息为:

count(std::vector<std::basic_string<char> >)':
error: no matching function for call to std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, __gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type&)'
  int cnt = count(a.begin(), a.end(), a[0]);

有什么帮助吗?这里有什么问题?

您提到了算法库,但请确保您已添加#include <algorithm> .

使用您的算法,它在代码上效果很好

#include <iostream>     // std::cout
#include <algorithm>    // std::count
#include <vector>       // std::vector
#include <string>       // std::vector
using namespace std;
int main () {
  // counting elements in container:
  vector<string> a {"abc", "def", "abc"};
  int cnt = count(a.begin(), a.end(), a.at(0));
  std::cout << a.at(0) << " " << cnt  << " times.n";
  return 0;
}

编译器标志:

-------------- Build: Debug in test (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -Wall -fexceptions -g -Weffc++ -std=c++14

此外,我的解决方案可能对您有用

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
    vector<string> stringList;
    stringList.push_back("abc");
    stringList.push_back("def");
    stringList.push_back("111 abc");
    string searchWord ("abc");
    int searchWordSize = searchWord.size();
    int count = 0;
    for (vector<string>::iterator iter = stringList.begin(); iter != stringList.end(); ++iter) {
        for (size_t pos = 0; pos < (*iter).length(); pos += searchWordSize) {
            pos = (*iter).find(searchWord, pos);
            if (pos != string::npos) ++count;
            else break;
        }
    }
    cout << "Count: " << count << endl;
    return 0;
}