std::vector to string with custom delimiter

前端 未结 9 1327
独厮守ぢ
独厮守ぢ 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:35

    faster variant:

    vector x = {"1", "2", "3"};
    string res;
    res.reserve(16);
    
    std::accumulate(std::begin(x), std::end(x), 0,
                    [&res](int &, string &s)
                    {
                        if (!res.empty())
                        {
                            res.append(",");
                        }
                        res.append(s);
                        return 0;
                   });
    

    it doesn't create interim strings, but just allocate memory once for the whole string result and appends each elem to the end of &res

提交回复
热议问题