2016-07-09 219 views
0

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

我使用内置的count功能从algorithm头,但得到一个奇怪的编译错误,我无法解决。

我的代码:

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

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

+2

[无法复制]我的解决方案可能是有用的( http://coliru.stacked-crooked.com/a/5192baa686d1f63a)。请发布[mcve]。 –

+0

你是否错过了包含'std :: vector'? –

+0

包含'std :: vector'。 – mtk

回答

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; 
} 
相关问题