join(文字列の連結)

概要:文字列の連結
ソース:join.hpp (ASCII CR/LF)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
template< class TInputIterator, class TDelimiter, class TOutputIterator > inline
TOutputIterator join(TInputIterator F_, TInputIterator L_, const TDelimiter& D_, TOutputIterator O_)
{
    if (F_ != L_) {
        *O_++ = *F_++;
        while (F_ != L_) {
            *O_++ = D_;
            *O_++ = *F_++;
        }
    }
    return O_;
}
template< class TChar, class TTraits, class TAllocator, class TInputIterator > inline
std::basic_string<TChar, TTraits, TAllocator> join(
    TInputIterator F_,
    TInputIterator L_,
    const std::basic_string<TChar, TTraits, TAllocator>& delimiter
) {
    std::basic_string<TChar, TTraits, TAllocator> S_;
    S_.resize(std::distance(F_, L_));
    static_cast<void>(join(F_, L_, std::inserter(S_, S_.end()), delimiter));
    return std::move(S_);
}
template< class TChar, class TTraits, class TAllocator, class TContainer > inline
std::basic_string<TChar, TTraits, TAllocator> join(
    const TContainer& C_,
    const std::basic_string<TChar, TTraits, TAllocator>& delimiter
) {
    std::basic_string<TChar, TTraits, TAllocator> S_;
    S_.resize(C_.size());
    static_cast<void>(join(C_.begin(), C_.end(), std::inserter(S_, S_.end()), delimiter));
    return std::move(S_);
}
ソース:使用例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// std::vector<std::string> の要素をカンマ区切りで連結したい。
std::string joinVectorString(const std::vector<std::string>& vstr, const char* delimiter = ",")
{
    // STLの場合
    // std::ostringstream ostr;
    // std::copy(vstr.begin(), vstr.end(), std::ostream_iterator< std::string, char >(ostr, delimiter));
    // return std::move(ostr.str());

    // poor_lib の場合
    std::string str;
    str.resize(vstr.size());
    return std::move(join(vstr.begin(), vstr.end(), std::inserter(str, str.end()), delimiter));
}