可以boost:algorithm :: join()concat一个容器的浮点数? [英] Can boost:algorithm::join() concat a container of floats?

查看:170
本文介绍了可以boost:algorithm :: join()concat一个容器的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Boost连接可用于连接可选用分隔符字符串分隔的字符串容器。在此stackovwerflow示例中: boost :: algorithm :: join 的一个很好的示例

我的STL技能很弱。我想知道是否还有使用相同的函数为一个数字的容器(浮点数,双精度,整数)?



还有一个stl的复制函数,有一个很好的例子:
C ++打印出向量的内容

但我不喜欢如何在每个元素后面添加分隔符字符串。我想只使用boost。



感谢。

解决方案

当然,您可以结合 boost :: algorithm :: join boost :: adapters :: transformed 将双精度转换为字符串,然后将它们连接在一起。 / p>

  #include< iostream& 
#include< vector>
#include< string>

#include< boost / algorithm / string / join.hpp>
#include< boost / range / adapter / transformed.hpp>

int main()
{
使用boost :: adapters :: transformed;
using boost :: algorithm :: join;

std :: vector< double> v {1.1,2.2,3.3,4.4};

std :: cout
<< join(v |
transformed(static_cast< std :: string(*)(double)>(std :: to_string)),
,);
}

输出:



< >

1.100000,2.200000,3.300000,4.400000



Boost join can be used to concatenate a container of strings optionally separated by a separator string. In this stackovwerflow example: A good example for boost::algorithm::join

My STL skills are weak. I'm wondering if there is anyway to use the same function for a container of numbers (floats, doubles, ints)? It just seems like there should some one- or two-liner to adapt it for other types.

There is also stl's copy function with a good example found here: C++ Printing out the contents of a vector

But I don't like how it adds the separator string after every element. I'd like to just use boost.

thanks.

解决方案

Sure, you can combine boost::algorithm::join and boost::adaptors::transformed to convert the doubles to strings and then join them together.

#include <iostream>
#include <vector>
#include <string>

#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/transformed.hpp>

int main()
{
    using boost::adaptors::transformed;
    using boost::algorithm::join;

    std::vector<double> v{1.1, 2.2, 3.3, 4.4};

    std::cout 
      << join( v | 
               transformed( static_cast<std::string(*)(double)>(std::to_string) ), 
               ", " );
}

Output:

1.100000, 2.200000, 3.300000, 4.400000

这篇关于可以boost:algorithm :: join()concat一个容器的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆