gpt4 book ai didi

C++ for_each 算法和字符串

转载 作者:行者123 更新时间:2023-11-28 06:45:34 26 4
gpt4 key购买 nike

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

这应该有效。

问题是你不能初始化一个string使用 char , 你需要另一个 string (C++ 字符串)或 const char* (C 字符串)。

此外,您实际上可以定义一个 std::unordered_map<char, unsigned int>


根据 Rob Kennedy 的评论编辑:

修复 const char* cc = &l 的错误使用.

现在正在调用 std::string 的正确 ctor .

关于C++ for_each 算法和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com