From 73742d362bf4e6089d8a3d0cbe956a4402a99253 Mon Sep 17 00:00:00 2001 From: sneaxiy <32832641+sneaxiy@users.noreply.github.com> Date: Mon, 17 Jan 2022 10:42:33 +0800 Subject: [PATCH] add convert func for string helper (#38600) --- paddle/fluid/string/string_helper.h | 16 ++++++++++++++++ paddle/fluid/string/string_helper_test.cc | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/paddle/fluid/string/string_helper.h b/paddle/fluid/string/string_helper.h index 4f1aee7c7ed..c52b7a99a77 100644 --- a/paddle/fluid/string/string_helper.h +++ b/paddle/fluid/string/string_helper.h @@ -193,6 +193,22 @@ std::string join_strings(const Container& strs, const std::string& delim) { return str; } +template +std::string join_strings(const Container& strs, DelimT&& delim, + ConvertFunc&& func) { + std::stringstream ss; + size_t i = 0; + for (const auto& elem : strs) { + if (i > 0) { + ss << delim; + } + ss << func(elem); + ++i; + } + + return ss.str(); +} + // A helper class for reading lines from file. A line buffer is maintained. It // doesn't need to know the maximum possible length of a line. diff --git a/paddle/fluid/string/string_helper_test.cc b/paddle/fluid/string/string_helper_test.cc index 4796bf7507a..67456e16a93 100644 --- a/paddle/fluid/string/string_helper_test.cc +++ b/paddle/fluid/string/string_helper_test.cc @@ -56,3 +56,10 @@ TEST(StringHelper, JoinStrings) { result = paddle::string::join_strings(v, " new "); EXPECT_EQ(result, "hello new world"); } + +TEST(StringHelper, JoinStringsWithConversion) { + std::vector v = {2, 3}; + auto result = + paddle::string::join_strings(v, ",", [](int x) { return x * x; }); + EXPECT_EQ(result, "4,9"); +} -- GitLab