2016-07-09 10 views
0

Meine Anforderung ist die Anzahl der Vorkommen einer Zeichenfolge in einem Vektor der Zeichenfolge zählen. Die zu durchsuchende Zeichenfolge befindet sich im 0-ten Index des Vektors.count Anzahl der Vorkommen einer Zeichenfolge in einem Vektor der Zeichenfolge

Ich benutze die eingebaute count Funktion von algorithm Header, aber immer einen komischen Kompilierungsfehler, den ich nicht lösen kann.

Mein Code:

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

Compilation Fehlermeldung lautet:

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

Jede Hilfe? Was ist das Problem hier?

+2

[reproduzieren kann nicht] (http://coliru.stacked-crooked.com/a/5192baa686d1f63a). Bitte poste ein [mcve]. –

+0

Vermissen Sie das Include für 'std :: vector'? –

+0

'std :: vector' ist enthalten. – mtk

Antwort

0

Sie erwähnten Algorithmusbibliothek, aber seien Sie sicher, dass Sie #include <algorithm> hinzugefügt haben.

Mit Ihrem Algorithmus funktioniert es gut hier auf 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 

Außerdem kann meine Lösung für Sie nützlich sein

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