加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何在元组上使用boost :: algorithm :: join?

发布时间:2020-12-16 09:41:18 所属栏目:百科 来源:网络整理
导读:boost :: algorithm :: join在std :: vector std :: string上提供了方便的连接. 您将如何扩展此功能以使用std :: vector std :: tuple std :: string,bool在进行连接之前,如果为true,则用单引号(对于字符串)包围结果. 这对于循环来说并不难,但我正在寻找一种
boost :: algorithm :: join在std :: vector< std :: string>上提供了方便的连接.

您将如何扩展此功能以使用std :: vector< std :: tuple< std :: string,bool>>在进行连接之前,如果为true,则用单引号(对于字符串)包围结果.

这对于循环来说并不难,但我正在寻找一种能够充分利用标准算法和C 11特性(例如lambdas)的解决方案.

如果可行的话,继续使用boost的连接:优雅/可读性/简洁性更重要.

#include <string>
#include <vector>
#include <tuple>
#include <boost/algorithm/string/join.hpp> 

int main( int argc,char* argv[] )
{
  std::vector<std::string> fields = { "foo","bar","baz" };
  auto simple_case = boost::algorithm::join( fields,"|" );

  // TODO join surrounded by single-quotes if std::get<1>()==true
  std::vector<std::tuple< std::string,bool >> tuples =
   { { "42",false },{ "foo",true },{ "3.14159",false } };

  // 42|'foo'|3.14159 is our goal
}

编辑

好吧,我在下面看了kassak的建议并看了一下boost :: transform_iterator() – 我被boost自己的文档中的例子的冗长所拖延,所以我尝试了std :: transform() – 它不像我那么短想要,但似乎有效.

回答

#include <string>
#include <vector>
#include <tuple>
#include <iostream>
#include <algorithm>
#include <boost/algorithm/string/join.hpp> 

static std::string
quoted_join( 
    const std::vector<std::tuple< std::string,bool >>& tuples,const std::string& join
)
{
    std::vector< std::string >  quoted;
    quoted.resize( tuples.size() );
    std::transform( tuples.begin(),tuples.end(),quoted.begin(),[]( std::tuple< std::string,bool > const& t ) 
        {
            return std::get<1>( t ) ? 
                "'" + std::get<0>(t) + "'" :
                std::get<0>(t);
        }
    );
  return boost::algorithm::join( quoted,join );
}

int main( int argc,char* argv[] )
{
  std::vector<std::tuple< std::string,bool >> tuples =
  { 
    std::make_tuple( "42",false ),std::make_tuple( "foo",true ),std::make_tuple( "3.14159",false ) 
  };

  std::cerr << quoted_join( tuples,"|" ) << std::endl;
}

解决方法

如果要使用join,可以在boost :: transform_iterator中包装集合,并在需要时添加引号

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读