Skip to content

Commit

Permalink
[core] Common util function refactor (#27743)
Browse files Browse the repository at this point in the history
### 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 <[email protected]>
Co-authored-by: barnasm1 <[email protected]>
  • Loading branch information
praasz and barnasm1 authored Nov 27, 2024
1 parent 9a5d3a5 commit 7f08db8
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions src/common/util/include/openvino/util/common_util.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,42 @@
namespace ov {
namespace util {

template <typename T>
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 <typename Container>
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 <typename T>
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<int>{1,3,5} -> "[ 1, 3, 5 ]"
* - std::vector<int>{} -> "[ ]"
*
* @param v Vector to be converted
* @return String contains
*/
template <typename T, typename A>
std::string vector_to_string(const std::vector<T, A>& v) {
return "[ " + ov::util::join(v) + " ]";
}

std::string to_lower(const std::string& s);
Expand Down Expand Up @@ -127,12 +145,7 @@ bool contains(const std::vector<T, A>& vec, const V& v) {
*/
template <typename T, typename A>
T product(std::vector<T, A> 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<T>());
}

/**
Expand Down

0 comments on commit 7f08db8

Please sign in to comment.