From 7f08db8669b63fe148d715cf7542edb0811f60fb Mon Sep 17 00:00:00 2001 From: Pawel Raasz Date: Wed, 27 Nov 2024 07:38:08 +0100 Subject: [PATCH] [core] Common util function refactor (#27743) ### Details: - Refactor `ov::util::join` to not do checks for each element. - Refactor `ov::util::vector_to_string` to not use `std::ostringstream` for temporary storage. - Refactor `ov::util::product` to use STL algorithms. ### Tickets: - N/A --------- Signed-off-by: Raasz, Pawel Co-authored-by: barnasm1 --- .../include/openvino/util/common_util.hpp | 49 ++++++++++++------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/src/common/util/include/openvino/util/common_util.hpp b/src/common/util/include/openvino/util/common_util.hpp index d068db373360b3..8a0b68a22ceb83 100644 --- a/src/common/util/include/openvino/util/common_util.hpp +++ b/src/common/util/include/openvino/util/common_util.hpp @@ -15,24 +15,42 @@ namespace ov { namespace util { -template -std::string join(const T& v, const std::string& sep = ", ") { +/** + * @brief Join container's elements to string using user string as separator. + * + * @param container Element to make joined string. + * @param sep User string used as separator. Default ", ". + * @return Joined elements as string. + */ +template +std::string join(const Container& container, const std::string& sep = ", ") { std::ostringstream ss; - size_t count = 0; - for (const auto& x : v) { - if (count++ > 0) { - ss << sep; + auto first = std::begin(container); + const auto last = std::end(container); + if (first != last) { + ss << *first; + ++first; + for (; first != last; ++first) { + ss << sep << *first; } - ss << x; } return ss.str(); } -template -std::string vector_to_string(const T& v) { - std::ostringstream os; - os << "[ " << ov::util::join(v) << " ]"; - return os.str(); +/** + * @brief Stringify the input vector. + * + * The vector is converted to the string as "[ element 0, element 1, ..., element N ]". + * Examples: + * - std::vector{1,3,5} -> "[ 1, 3, 5 ]" + * - std::vector{} -> "[ ]" + * + * @param v Vector to be converted + * @return String contains + */ +template +std::string vector_to_string(const std::vector& v) { + return "[ " + ov::util::join(v) + " ]"; } std::string to_lower(const std::string& s); @@ -127,12 +145,7 @@ bool contains(const std::vector& vec, const V& v) { */ template T product(std::vector const& vec) { - if (vec.empty()) - return 0; - T ret = vec[0]; - for (size_t i = 1; i < vec.size(); ++i) - ret *= vec[i]; - return ret; + return vec.empty() ? T{0} : std::accumulate(vec.begin(), vec.end(), T{1}, std::multiplies()); } /**