使用std :: count来计算字符串向量中某些字符的数量(C ++)

时间:2017-03-12 17:51:11

标签: c++ string vector

我对所有关于此主题的类似问题进行了彻底的观察(我认为),但我无法找到适合我的解决方案。

我需要计算字符串向量内的特定字母(ch)的数量,bookFile(每个字符串包含多个单词和空格)并测试ch出现次数是否大于1。

这是我现在所拥有的(字符存储在向量中,messageFile):

char ch = messageFile[i];
if(count(bookFile.begin(), bookFile.end(), ch) > 1){
      // do something if there are more than 1 
}

但是我在编译时收到此错误:

Error   C2678   binary '==': no operator found which takes a left-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' (or there is no acceptable conversion) bcencode    c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility 3310    

我还是c ++的新手,所以我不确定会出现什么问题。

更新

我最终用这个来计算Vector中的字母数。谢谢@ Kolyan1

int countLetters(vector<string> &b, char ch) {
    int counter = 0;

    for (auto it = b.begin(); it != b.end(); ++it) {
        string temp_string = *it; //not strictly necessary
        counter += count(temp_string.begin(), temp_string.end(), ch);
    }

    return counter;
}

2 个答案:

答案 0 :(得分:1)

你遇到的问题是bookFile不是一个字符串。所以,您可以使用一些外部库:@ Jarod42发布。

(即以下内容可行:

if( count(messageFile.begin(), messageFile.end(), ch) > 0){
    cout << "YOU MADE IT" << endl;
}

为了使你的情况起作用,你需要遍历bookfile并按如下方式添加每个字符串的计数:

//assuming ch is char
//and assuming bookFile is std::vector<std::string>
int counter = 0;
for(auto it = bookFile.begin();it!=bookFile.end();++it){
    string temp_string = *it; //not strictly necessary
    counter += count(temp_string.begin(),temp_string.end(),ch);
}
if(counter>1){
 //DO Whatever
}

我希望这会有所帮助。

答案 1 :(得分:0)

使用range-v3,它只是

std::vector<std::string> words /* = ... */;
const auto count = ranges::count(words | ranges::view::join, ch);

Demo

相关问题