为什么我不能将 cend() 和 cbegin() 传递给count_if?
Why can't I pass cend() and cbegin() to count_if?
我正在尝试计算向量中长度大于 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
上。 begin
和 end
在 const
向量上调用时将返回const
迭代器。因此,当我删除const
时,它实际上是cbegin
和cend
。我之所以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> ]
你是对的,因为你的vector
是const
,你的迭代器也将const
。
但因此,谓词函数的参数也必须const
。
您需要:const std::string &s
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟
- 访问可能不存在的const vector成员- try/catch或if (count != 0)