1 #ifndef __JOIN_H
2 #define __JOIN_H
3 
4 // functions to split a string by a specific delimiter
5 #include <string>
6 #include <vector>
7 #include <sstream>
8 #include <string.h>
9 
10 // join a vector of elements by a delimiter object.  ostream<< must be defined
11 // for both class S and T and an ostream, as it is e.g. in the case of strings
12 // and character arrays
13 template<class S, class T>
join(std::vector<T> & elems,S & delim)14 std::string join(std::vector<T>& elems, S& delim) {
15     std::stringstream ss;
16     typename std::vector<T>::iterator e = elems.begin();
17     if (e != elems.end()) {
18         ss << *e++;
19         for (; e != elems.end(); ++e) {
20             ss << delim << *e;
21         }
22     }
23     return ss.str();
24 }
25 
26 // same for lists
27 template<class S, class T>
join(std::list<T> & elems,S & delim)28 std::string join(std::list<T>& elems, S& delim) {
29     std::stringstream ss;
30     typename std::list<T>::iterator e = elems.begin();
31     if (e != elems.end()) {
32         ss << *e++;
33         for (; e != elems.end(); ++e) {
34             ss << delim << *e;
35         }
36     }
37     return ss.str();
38 }
39 
40 #endif
41