Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::count passes constants to lambda, not chars when working on string?

Tags:

c++

stl

I have a string and want to count for certain elements in it. I wrote a code:

#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    string a;
    cin >> a;
    int b = count(a.begin(), a.end(), [](char g) {return (g == '"' or g == '.' or g == ',' or g == ';' or g == ':' or g == '!' or g == '?');});
    cout << b;
}

Since std::count should return number of elements that are equal to another element (specified as third parameter of the function) or that meets certain function by passing elements one-by-one to that function, I expect it to pass chars to my lambda function. I wrote mostly as in last example on CPPreference, but looks like it works not in a way I expect it to be. During compilation I face a error in my lambda function:

/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/predefined_ops.h:241:17: error: invalid operands to binary expression ('char' and 'const (lambda at /home/keddad/CLionProjects/olimp/main.cpp:12:39)') { return *__it == _M_value; }

So looks like count passes some kind of constant to my little function, which is later tries to compare it with char (and drops error). How can I make my code work? How does std::count actually works?

like image 969
keddad Avatar asked Apr 09 '26 17:04

keddad


1 Answers

std::count takes three parameters: two iterators and a value to compare against. So it's trying to compare the lambda to each character in the string.

std::count_if takes three parameters: two iterators and a "callable" to be called for each character in the string.

As @piotr-skotnicki said, I suspect you want to use count_if.

like image 133
Marshall Clow Avatar answered Apr 11 '26 07:04

Marshall Clow