C++ for_each algo and string

C++ for_each algo and string

本文关键字:and string algo each for C++      更新时间:2023-10-16

我尝试使用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
})