Can boost:algorithm::join() concat a container of floats?

后端 未结 2 1368
花落未央
花落未央 2020-12-31 05:08

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

2条回答
  •  無奈伤痛
    2020-12-31 05:43

    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.

    std::accumulate allows to do a fold over any (input) iterator range, using a binary function which can take different types for the "accumulator" and the next item. In your case: A function taking a std::string and a double (or whatever) that concatenates the given std::string with the result of std::to_string on the second parameter.

    template
    std::string contents_as_string(Container const & c,
                                   std::string const & separator) {
      if (c.size() == 0) return "";
      auto fold_operation = [&separator] (std::string const & accum,
                                          auto const & item) {
        return accum + separator + std::to_string(item);};
      return std::accumulate(std::next(std::begin(c)), std::end(c),
                             std::to_string(*std::begin(c)), fold_operation);
    }
    

    As you can see, this is completely independent of the value type of the container. As long as you can pass it to std::to_string you're good. Actually, above code is a slight variation of the example presented for std::accumulate.

    Demo of above function:

    int main() {
      std::vector v(4);
      std::iota(std::begin(v), std::end(v), 0.1);
      std::cout << contents_as_string(v, ", ") << std::endl;
    
      std::vector w(5);
      std::iota(std::begin(w), std::end(w), 1);
      std::cout << contents_as_string(w, " x ") << " = "
        << std::accumulate(std::begin(w), std::end(w), 1, std::multiplies{})
        << std::endl;
    }
    

    0.100000, 1.100000, 2.100000, 3.100000
    1 x 2 x 3 x 4 x 5 = 120

提交回复
热议问题