Search code examples
c++boost

Using boost::format with std::vector


It is possible to use boost::format with std::vector<std::string> like below.

    std::vector<std::string> name = {"some", "name"};
    boost::format("%s, %s") % name[0] % name[1];

Since I have a large vector, I would like to use them together without manually writing indices:

    std::vector<std::string> name = {"some", "name"};
    boost::format("%s, %s") % name;

Using something like boost::algorithm::join to join strings is not an option. Is there a way to achieve string formatting with a vector without explicitly writing indices?


Solution

  • Check out this sample:

    #include <vector>
    #include <string>
    #include <iostream>
    
    #include <boost/format.hpp>
    
    auto format_vector(boost::format fmt, const std::vector<std::string> &v) {
        for(const auto &s : v) {
            fmt = fmt % s;
        }
        return fmt;
    }
    
    int main() {
        std::vector<std::string> name = {"some", "name"};
        std::cout << format_vector(boost::format("%s, %s"), name) << "\n";
        return 0;
    }
    

    (https://godbolt.org/z/nGqW9h)

    Operator% of format stores partially parsed string internally, and returns itself - so it can be chained as in regular usage. We can store this partial state to operate in loop with that.

    Although, you still need to take care of proper %s count in format string!