C++ for_each algo and string
C++ for_each algo and string
我尝试使用for_each,
循环遍历字符串的每个字母std::unordered_map<std::string, unsigned int> dico;
std::for_each(str.begin(),str.end(),[&](std::string l){
if(dico.count(l) == 0){
' DO SOMETHING HERE
})
然而,我得到了一个错误消息:
Error 2 error C2664: 'void `anonymous-namespace'::<lambda2>::operator ()(std::string) const' : cannot convert parameter 1 from 'const char' to 'std::string'
我试图改变到char l
,然而,它会打破dico.count(l)
。相反,我看到其他人用for loop
代替。这个解决方案奏效了。然而,我想知道为什么for_each
不会在这里工作。
std::unordered_map<std::string, unsigned int> dico;
dico["a"] = 1;
dico["b"] = 1;
dico["c"] = 1;
std::string str("abcd");
std::for_each(str.begin(),str.end(),[&](char l){
std::string s(1,l); // fixed
if(dico.count(s) == 0){
std::cout << "1" << std::endl;
}});
这应该可以工作。
问题是你不能用char
初始化string
,你需要另一个string
(c++字符串)或const char*
(C字符串)。
除此之外,你还可以定义一个std::unordered_map<char, unsigned int>
?
根据Rob Kennedy的评论编辑:
修复const char* cc = &l
的错误使用。
现在调用std::string
的正确变量
首先,str到底是什么?它的类型是什么?它包含什么?
第二,dico不包含任何内容,因此,即使你的代码是正确的并且确实编译了,该分支也会对str中的每个项执行。
第三,首先要搞清楚逻辑。使用一个简单的for循环来完成。代码越复杂,你花在找出问题上的时间就越长。
最后,如果你只是想使用一些c++ 11的特性,从简单的开始,比如for range循环:)
for(auto l : str){
if(dico.count(l) == 0){
// do something
}
}
std::unordered_map::value_type is pair不是字符串!
std::unordered_map<std::string, unsigned int> dico;
std::for_each(str.begin(),str.end(),[&](pair<std::string, unsigned int> l){
if(dico.count(l.first) == 0){
' DO SOMETHING HERE
})
相关文章:
- cppcheck在const std::string[]上引发警告
- std::time_point from and to std::string
- C++20 with u8, char8_t and std::string
- C++ - vsprintf_s and std::string?
- map<string, class> using and couting
- std::string and const char *
- jni String to *char and java.lang.UnsatisfiedLinkError:
- std::string, std::wstring and UTF8
- Concatenate boost::array and std::string
- std::string and move_iterator
- stringList and string
- std::string and stdarg.h
- C++ for_each algo and string
- Interchanging const char* and std::string
- Compare std::wstring and std::string
- string and const char* and .c_str()?
- char and String in c++
- Round Double and Cast to String
- std::string to LPBYTE and RegEnumValueA
- std::string::reserve() and std::string::clear() conundrum