[PATCH] Python-like join function for string lists

Joerg Sonnenberger joerg at NetBSD.org
Tue Sep 3 12:46:06 PDT 2013



================
Comment at: include/llvm/ADT/StringExtras.h:188-190
@@ +187,5 @@
+  size_t Len = 0;
+  for (iter I = Begin; I != End; ++I)
+    Len += (*Begin).size() + Separator.size();
+  Len -= Separator.size();
+  S.reserve(Len);
----------------
Shankar Kalpathi Easwaran wrote:
> We can use std::distance here
This way it mirrors the main loop, which makes it simpler, IMO. The use of std::distance would just allow to move the Separator.size() addend out of the loop and replace it with a multiplication.

================
Comment at: include/llvm/ADT/StringExtras.h:163-177
@@ -161,1 +162,17 @@
 
+template <typename iter>
+static inline std::string join_impl(iter Begin, iter End, StringRef Separator,
+  std::input_iterator_tag)
+{
+  std::string S;
+  if (Begin == End)
+    return S;
+
+  S += (*Begin);
+  while (++Begin != End) {
+    S += Separator;
+    S += (*Begin);
+  }
+  return S;
+}
+
----------------
Shankar Kalpathi Easwaran wrote:
> why would anyone use this version over the other ?
The pre-computation of the output size requires that iterating twice. If the given iterator is not a forward iteratior, but e.g. a stream, it will give incorrect results silently. This was requested on IRC.


http://llvm-reviews.chandlerc.com/D1585



More information about the llvm-commits mailing list