Skip to content

Commit fa1c716

Browse files
author
MacroFake
committed
Make Join() util work with any container type
Also, remove helper that is only used in tests.
1 parent faf8da3 commit fa1c716

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

src/test/util_tests.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,9 @@ BOOST_AUTO_TEST_CASE(util_Join)
244244

245245
// Version with unary operator
246246
const auto op_upper = [](const std::string& s) { return ToUpper(s); };
247-
BOOST_CHECK_EQUAL(Join<std::string>({}, ", ", op_upper), "");
248-
BOOST_CHECK_EQUAL(Join<std::string>({"foo"}, ", ", op_upper), "FOO");
249-
BOOST_CHECK_EQUAL(Join<std::string>({"foo", "bar"}, ", ", op_upper), "FOO, BAR");
247+
BOOST_CHECK_EQUAL(Join(std::list<std::string>{}, ", ", op_upper), "");
248+
BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo"}, ", ", op_upper), "FOO");
249+
BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo", "bar"}, ", ", op_upper), "FOO, BAR");
250250
}
251251

252252
BOOST_AUTO_TEST_CASE(util_ReplaceAll)

src/util/string.h

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,27 +58,30 @@ void ReplaceAll(std::string& in_out, const std::string& search, const std::strin
5858
}
5959

6060
/**
61-
* Join a list of items
61+
* Join all container items. Typically used to concatenate strings but accepts
62+
* containers with elements of any type.
6263
*
63-
* @param list The list to join
64-
* @param separator The separator
65-
* @param unary_op Apply this operator to each item in the list
64+
* @param container The items to join
65+
* @param separator The separator
66+
* @param unary_op Apply this operator to each item
6667
*/
67-
template <typename T, typename BaseType, typename UnaryOp>
68-
auto Join(const std::vector<T>& list, const BaseType& separator, UnaryOp unary_op)
68+
template <typename C, typename S, typename UnaryOp>
69+
auto Join(const C& container, const S& separator, UnaryOp unary_op)
6970
{
70-
decltype(unary_op(list.at(0))) ret;
71-
for (size_t i = 0; i < list.size(); ++i) {
72-
if (i > 0) ret += separator;
73-
ret += unary_op(list.at(i));
71+
decltype(unary_op(*container.begin())) ret;
72+
bool first{true};
73+
for (const auto& item : container) {
74+
if (!first) ret += separator;
75+
ret += unary_op(item);
76+
first = false;
7477
}
7578
return ret;
7679
}
7780

78-
template <typename T, typename T2>
79-
T Join(const std::vector<T>& list, const T2& separator)
81+
template <typename C, typename S>
82+
auto Join(const C& container, const S& separator)
8083
{
81-
return Join(list, separator, [](const T& i) { return i; });
84+
return Join(container, separator, [](const auto& i) { return i; });
8285
}
8386

8487
/**

0 commit comments

Comments
 (0)