implement iterator based join_string()
[libi2ncommon] / src / stringfunc.hxx
index 29b8aba..bb5a960 100644 (file)
@@ -34,7 +34,9 @@ on this file might be covered by the GNU General Public License.
 #ifndef __STRINGFUNC_HXX
 #define __STRINGFUNC_HXX
 
+#include <stdio.h>
 #include <list>
+#include <numeric>
 #include <set>
 #include <vector>
 #include <string>
@@ -130,21 +132,46 @@ std::list< std::string > split_string(
    const std::string& trim_list= std::string()
 );
 
+struct concatenator {
+    std::string delim;
 
-std::string join_string(
-   const std::list< std::string >& parts,
-   const std::string& delimiter = "\n"
-);
+    concatenator (const std::string &delim) : delim (delim) { }
 
-std::string join_string(
-   const std::vector< std::string >& parts,
-   const std::string& delimiter = "\n"
-);
+    inline std::string operator() (const std::string &acc, const std::string &elt) const
+    { return acc + delim + elt; }
+};
 
-std::string join_string(
-   const std::set< std::string >& parts,
+template<typename Iter>
+std::string
+join_string (
+    Iter first,
+    Iter last,
+    const std::string &delimiter = "\n"
+)
+{
+    if (first == last) { return ""; }
+
+    const std::string &init = *first++;
+    if (first == last) { return init; }
+
+    return std::accumulate (first, last, init, concatenator (delimiter));
+}
+
+/**
+ * @brief joins a container of strings into a single string.
+ *
+ * This funtion is (basically) the reverse operation of @a split_string.
+ *
+ * @param parts         the container of strings.
+ * @param delimiter     the delimiter to insert between the strings.
+ * @return              the joined string.
+ */
+template<typename Cont>
+inline std::string join_string(
+   const Cont& parts,
    const std::string& delimiter = "\n"
-);
+)
+{ return join_string (parts.begin (), parts.end (), delimiter); }
 
 std::string join_string(
    const char *const parts [],