下面的表达式对 for_each()
有效吗?
for_each(v,[](string x){
cout<<x<<endl;
});
引用:CppCoreGuidelines.md#p3-express-intent
上面的表达式抛出以下错误:
error: no matching function for call to ‘for_each(std::vector<std::__cxx11::basic_string<char> >&, main()::<lambda(std::__cxx11::string)>)’ }); ^ In file included from /usr/include/c++/5/algorithm:62:0, from test.cpp:4: /usr/include/c++/5/bits/stl_algo.h:3761:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct) for_each(_InputIterator __first, _InputIterator __last, _Function __f) ^ /usr/include/c++/5/bits/stl_algo.h:3761:5: note: template argument deduction/substitution failed: test.cpp:60:6: note: deduced conflicting types for parameter ‘_IIter’ (‘std::vector<std::__cxx11::basic_string<char> >’ and ‘main()::<lambda(std::__cxx11::string)>’) });
最佳答案
好吧,核心指南提到了 for_each
,而不是 std::for_each
。所以很难回答你的问题...
如果他们实际上指的是
std::for_each
,那么这将是一个打字错误,因为它需要两个迭代器 - 除非他们指的是 future 版本的std::for_each
that might be introduced with the Ranges proposals .如果他们指的是通用
for_each
,那么它可能只是:template <typename TContainer, typename TF> void for_each(TContainer&& c, TF&& f) { for(auto&& x : c) f(x); }
关于c++ - C++ 表达式 for_each(v, [](string x) 在语法上是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633303/