【问题标题】:Using std::count to Count number of certain char in a vector of Strings (C++)使用 std::count 计算字符串向量中某些字符的数量(C++)
【发布时间】:2017-03-12 17:51:11
【问题描述】:

我已经彻底(我认为)查看了有关此主题的所有类似问题,但找不到适合我的解决方案。

我需要计算字符串向量 bookFile(每个字符串包含多个单词和空格)中特定字母 (ch) 的数量,并测试 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++ 新手,所以我不确定出了什么问题。

更新

我最终用这个来计算向量中的字母数量。谢谢@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;
}

【问题讨论】:

  • 我是string的向量,你正在搜索char,你不应该搜索string吗?
  • 我需要在字符串中找到一个字母(ch)。
  • 字符串?哪一个 ?你有一个完整的std::vector strings
  • @P0W vector 他需要双循环一个到迭代器字符串向量,另一个到迭代器字符在字符串中
  • @AnkurJyotiPhukan 是的,我明白了,但我不会盲目地假设,只是后来意识到 OP 意味着完全不同的东西,这种情况经常发生

标签: c++ string vector


【解决方案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
}

我希望这会有所帮助。

【讨论】:

  • 对于 pre C++11(即如果不支持 auto)使用:for(vector::iterator it = bookFile.begin(); ...
【解决方案2】:

使用range-v3,它只是

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

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多