Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fmt custom formatting for vector of pairs

Tags:

c++

fmt

Code snippet

std::vector<std::pair<int, std::string>> myVec;
myVec.emplace_back(12,"A");
myVec.emplace_back(13,"B");
myVec.emplace_back(14,"C");

I would like to use following to produce output like "12=A|13=B|14=C"

fmt::format("{}", fmt::join(myVec, "|"));

Any idea how to achieve this?

like image 767
user1658476 Avatar asked Oct 28 '25 03:10

user1658476


1 Answers

You can do it as follows (godbolt):

auto v = std::views::transform(myVec, [](const auto& p) {
  return fmt::format("{}={}", p.first, p.second);
});
auto s = fmt::format("{}", fmt::join(v, "|"));

If you need to do it multiple times you could also put this in a function or provide a view type with a custom formatter.

like image 50
vitaut Avatar answered Oct 29 '25 19:10

vitaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!