为什么我不能将 cend() 和 cbegin() 传递给count_if?

Why can't I pass cend() and cbegin() to count_if?

本文关键字:count if 不能 cend 为什么 cbegin      更新时间:2023-10-16

我正在尝试计算向量中长度大于 6 的字符串数。这很简单,但我正在尝试使用 algorithm 库中的count_if来做到这一点。所以这是我的代码:

int string_size_check(const std::vector<std::string> &v, unsigned int size){
    return std::count_if(v.begin(), v.end(), [size] (std::string &s)->bool{ return s.size() > size; });
}
int main(){
    std::vector<std::string> v = { "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefg" };
    std::cout << string_size_check(v, 6);
}

string_size_check是该功能。我使用了一个 lambda 作为谓词。
此代码未编译。问题出在第一个参数中的const上。 beginendconst 向量上调用时将返回const迭代器。因此,当我删除const时,它实际上是cbegincend。我之所以const参数,是因为 AFAIK count_if不会更改容器中的内容。
我不知道为什么将const迭代器传递给count_if不起作用。
编辑:这是Visual Studio 2013中的错误消息

    c:program files (x86)microsoft visual studio 12.0vcincludealgorithm(97): error C2664: 'bool string_size_check::<lambda_fed0cfd76fd966b8c62fe345d7e88af2>::operator ()(std::string &) const' : cannot convert argument 1 from 'const std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'std::string &'
1>          Conversion loses qualifiers
1>          c:program files (x86)microsoft visual studio 12.0vcincludealgorithm(109) : see reference to function template instantiation 'std::iterator_traits<const std::basic_string<char,std::char_traits<char>,std::allocator<char>> *>::difference_type std::_Count_if<const std::basic_string<char,std::char_traits<char>,std::allocator<char>>*,_Pr>(_InIt,_InIt,_Pr)' being compiled
1>          with
1>          [
1>              _Pr=string_size_check::<lambda_fed0cfd76fd966b8c62fe345d7e88af2>
1>  ,            _InIt=const std::basic_string<char,std::char_traits<char>,std::allocator<char>> *
1>          ]
1>          c:usersenterdocumentsvisual studio 2013projectswin32testwin32testsource.cpp(7) : see reference to function template instantiation '__w64 int std::count_if<std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>>>,string_size_check::<lambda_fed0cfd76fd966b8c62fe345d7e88af2>>(_InIt,_InIt,_Pr)' being compiled
1>          with
1>          [
1>              _InIt=std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>>>
1>  ,            _Pr=string_size_check::<lambda_fed0cfd76fd966b8c62fe345d7e88af2>
1>          ]

你是对的,因为你的vectorconst,你的迭代器也将const

但因此,谓词函数的参数也必须const

您需要:const std::string &s