Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boost::format with std::vector

Tags:

c++

boost

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?

like image 975
abyesilyurt Avatar asked Jun 07 '26 18:06

abyesilyurt


2 Answers

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!

like image 185
Jakub Piskorz Avatar answered Jun 10 '26 08:06

Jakub Piskorz


This is not answering the question, but libfmt likely has what you hope for:

#include <vector>
#include <fmt/ranges.h>

int main() {
  std::vector<int> v = {1, 2, 3};
  fmt::print("{}\n", v);
}

Prints

{1, 2, 3}
like image 31
sehe Avatar answered Jun 10 '26 08:06

sehe