鱼C论坛

 找回密码
 立即注册
查看: 1116|回复: 1

[已解决]C++谓词

[复制链接]
发表于 2023-11-15 21:21:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
bool com(const string& a){
        return a.size() < 5;
}
int main()
{  

        vector<string> name = {"namenamename","zhangzhang","yuyu"};
        for (auto &a : name){
                auto aa = partition(a.begin(),a.end(),com);
                for (;aa<=a.end();aa++){
                        cout <<*aa<<" ";
                }
        }
        return 0;
}

std::__cxx11::basic_string<char>&' from expression of type 'char'
      else if (!bool(__pred(*__last)))

这里一直再报这个错误,这是为什么?
最佳答案
2023-11-15 21:21:22
这个程序中出现错误是因为 partition 函数的使用有误。 partition 函数是用来对范围内的元素进行重新排列,使得满足指定条件的元素在前面,不满足条件的元素在后面,并返回第一个不满足条件的元素的迭代器。在这个例子中, partition 函数被错误地用在了 string 对象上,而不是 vector<string> 上。

正确的做法是将 partition 函数应用于 vector<string> ,并且在lambda表达式中传递 com 谓词函数来进行分区。下面是修改后的代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

bool com(const std::string& a){
    return a.size() < 5;
}

int main()
{  
    std::vector<std::string> name = {"namenamename", "zhangzhang", "yuyu"};
    for (auto &a : name){
        auto aa = std::partition(a.begin(), a.end(), com);
        for (auto it = a.begin(); it != aa; ++it){
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

这样修改后,程序将正确地输出每个字符串中长度小于5的部分。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-15 21:21:22 | 显示全部楼层    本楼为最佳答案   
这个程序中出现错误是因为 partition 函数的使用有误。 partition 函数是用来对范围内的元素进行重新排列,使得满足指定条件的元素在前面,不满足条件的元素在后面,并返回第一个不满足条件的元素的迭代器。在这个例子中, partition 函数被错误地用在了 string 对象上,而不是 vector<string> 上。

正确的做法是将 partition 函数应用于 vector<string> ,并且在lambda表达式中传递 com 谓词函数来进行分区。下面是修改后的代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

bool com(const std::string& a){
    return a.size() < 5;
}

int main()
{  
    std::vector<std::string> name = {"namenamename", "zhangzhang", "yuyu"};
    for (auto &a : name){
        auto aa = std::partition(a.begin(), a.end(), com);
        for (auto it = a.begin(); it != aa; ++it){
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

这样修改后,程序将正确地输出每个字符串中长度小于5的部分。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-5 07:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表