Namaran

Code daily. Without assist.

2026-09-09

join.cpp

#include <string>
#include <string_view>
#include <vector>

std::string join(const std::vector<std::string>& words, std::string_view sep) {
}

words の要素を先頭から順に、あいだに sep を挟んでつないだ文字列を返す join を書いてください。区切りは要素と要素のあいだにだけ入り、末尾には付きません。words が空なら空文字列を、1要素ならその要素だけを返します。join({"id", "name", "email"}, ", ") → "id, name, email"、join({"users"}, ", ") → "users"、join({}, ", ") → ""

Reference
std::string join(const std::vector<std::string>& words, std::string_view sep) {
    std::string out;
    for (bool first = true; const auto& w : words) {
        if (!first) {
            out += sep;
        }
        out += w;
        first = false;
    }
    return out;
}

範囲for文で要素を順に out へ足し、2つ目以降の要素の前にだけ sep を足します。最初の要素かどうかを覚えるフラグ first は、C++20から書ける範囲for文の初期化文に置いています。こうすると first の有効範囲がループの中だけになり、関数の残りの部分からは見えません。

要素は const auto& で受けているので、std::string をコピーしません。out += sep は std::string_view を受け取る operator+= で、sep の中身を追記します。

これは参考実装であり、唯一の正解ではありません。words が空でなければ先頭の要素を先に入れ、残りを std::views::drop(words, 1) で回して毎回 sep と要素を足す書き方もあります。