gpt4 book ai didi

c++ - 为什么在 C++ 函数 boost::algorithm::join_if 中抛出 std::bad_cast 异常?

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:47 27 4
gpt4 key购买 nike

我在我的代码中发现了一个问题。当我使用 boost::algorithm::join 时它正常工作,但是当我使用 boost::algorithm::join_if 时抛出一个 bad_cast。我的代码如下:

#include <iostream>
#include <string>
#include <list>
#include <boost/algorithm/string.hpp>

using namespace std;


main(int argc, char **argv)
{
list<string> players;
players.push_back("ProPlayer98");
players.push_back("King of Darkness");
players.push_back("Noob999");
players.push_back("Daily Queen");

cout << boost::algorithm::join(players, ", ") << endl; // it works
cout << boost::algorithm::join_if(players, ", ", boost::is_alpha()) << endl; // bad_cast
}

我的程序的输出是:

ProPlayer98, King of Darkness, Noob999, Daily Queen
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Abort trap (core dumped)

我曾多次使用 boost::algorithm 函数来处理文本,但我只使用了几次 predicates , 但从未发生过这样的问题。

我什至尝试将 const char* 替换为 std::string:

cout << boost::algorithm::join_if(players, string(", "), boost::is_alpha()) << endl;

但问题还是一样。

编辑:我想要一个在早于 C++11 的 C++ 中也能工作的解决方案

最佳答案

boost::is_alpha 用于字符

使用如下:-

cout << boost::algorithm::join_if(players, ", ",
[](const std::string & s){
return boost::all(s,boost::is_alpha());
}) << endl;

显然,您不会得到任何输出,因为空格 ' ' 和数字出现在 players 中。

改用 boost::alnum()

关于c++ - 为什么在 C++ 函数 boost::algorithm::join_if 中抛出 std::bad_cast 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18755129/

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