mtk
mtk

Reputation: 13709

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

My requirement is to count the number of occurences of a string inside a vector of string. The string to be searched is at 0th index of the vector.

I am using the inbuilt count function from algorithm header, but getting a weird compilation error, which I am not able to resolve.

My Code:

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

Compilation error message is:

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]);

Any help? What is the issue here?

Upvotes: 0

Views: 8064

Answers (1)

You mentioned algorithm library but be sure you have added #include <algorithm>.

With your algorithm it works well here on code

#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;
}

Compiler flag:

-------------- Build: Debug in test (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -Weffc++ -std=c++14

Besides, my solution may be useful for you

#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;
}

Upvotes: 1

Related Questions