Mercurial > code
comparison misc/join.hpp @ 570:dcef88285f8c
Misc: add join function
author | David Demelier <markand@malikania.fr> |
---|---|
date | Wed, 29 Jun 2016 19:12:10 +0200 |
parents | |
children | c79a501782b0 |
comparison
equal
deleted
inserted
replaced
569:b1c4933afcd0 | 570:dcef88285f8c |
---|---|
1 /* | |
2 * join.hpp -- join lists into a string | |
3 * | |
4 * Copyright (c) 2013-2016 David Demelier <markand@malikania.fr> | |
5 * | |
6 * Permission to use, copy, modify, and/or distribute this software for any | |
7 * purpose with or without fee is hereby granted, provided that the above | |
8 * copyright notice and this permission notice appear in all copies. | |
9 * | |
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
17 */ | |
18 | |
19 /** | |
20 * Join values by a separator and return a string. | |
21 * | |
22 * \param first the first iterator | |
23 * \param last the last iterator | |
24 * \param delim the optional delimiter | |
25 * \return the string | |
26 */ | |
27 template <typename InputIt, typename DelimType = char> | |
28 std::string join(InputIt first, InputIt last, DelimType delim = ':') | |
29 { | |
30 std::ostringstream oss; | |
31 | |
32 if (first != last) { | |
33 oss << *first; | |
34 | |
35 while (++first != last) | |
36 oss << delim << *first; | |
37 } | |
38 | |
39 return oss.str(); | |
40 } | |
41 | |
42 /** | |
43 * Convenient overload. | |
44 * | |
45 * \param list the initializer list | |
46 * \param delim the delimiter | |
47 * \return the string | |
48 */ | |
49 template <typename T, typename DelimType = char> | |
50 inline std::string join(std::initializer_list<T> list, DelimType delim = ':') | |
51 { | |
52 return join(list.begin(), list.end(), delim); | |
53 } |