LoginSignup
2
3

More than 5 years have passed since last update.

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

Posted at
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のパラメータ部分をさくっと作りたかった
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3