std::vector to string with custom delimiter

前端 未结 9 1285
独厮守ぢ
独厮守ぢ 2020-12-03 16:42

I would like to copy the contents of a vector to one long string with a custom delimiter. So far, I\'ve tried:

// .h
string getLabe         


        
9条回答
  •  抹茶落季
    2020-12-03 17:32

    string join(const vector & v, const string & delimiter = ",") {
        string out;
        if (auto i = v.begin(), e = v.end(); i != e) {
            out += *i++;
            for (; i != e; ++i) out.append(delimiter).append(*i);
        }
        return out;
    }
    

    A few points:

    • you don't need an extra conditional to avoid an extra trailing delimiter
    • make sure you don't crash when the vector is empty
    • don't make a bunch of temporaries (e.g. don't do this: x = x + d + y)

提交回复
热议问题