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

标签 c++ join boost string-algorithm

我在我的代码中发现了一个问题。当我使用 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/

相关文章:

c++ - 使用 gstreamer 的 appsrc 和 appsink 修改视频

c++ - QT:在选择文件的目录上启动默认浏览器

c++ - 不区分大小写的 std::string.find()

node.js - 有没有办法在 Sequelize 中将一个表的一个属性与另一个表的任何属性相关联?

c++ - 一个多索引,其中一个索引是整个集合的一个子集

c++ - 从 C++ 函数返回不同的类型

MySQL JOIN 查询 - 右表中的一行对应左表中的每一行,并优先考虑所包含的数据

mySQL JOIN 用法

c++ - 带有 BOOST 的简单代理程序

c++ - 可能的编译器错误 : Weird results using boost bessel functions with Intel compiler between two machines?