Posted at

std::accumulateをつかって、{"A","B","C"}な配列を指定文字で結合するサンプル

More than 3 years have passed since last update.


Implementation


#include <vector>
#include <numeric>
#include <algorithm>

std::string Joint(std::vector<std::string>& container, const std::string& delim)
{
return std::accumulate(
container.begin() + 1
, container.end()
, container[0]
, [&delim](const std::string& a, const std::string& b) {
if (b.empty())
return a;
return a + delim + b;
});
}



Usage

const std::vector<std::string> abc = { "A", "B", "C" };

const std::vector<std::string> param = {
"hoge=1",
"",
"fuga=2",
"",
"foo=3",
};

Joint(abc, std::string("&"); // "A&B&C"

Joint(param, std::string("-"); // "hoge=1&fuga=2&foo=3"



  • 空文字はスキップさせたかった

  • Web APIのパラメータ部分をさくっと作りたかった