部分文字列の組み合わせをC++で

これのC++版のメモ。

#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>

std::vector<std::vector<std::string> > enum_cons(std::vector<std::string> v, int n) {
  std::vector<std::vector<std::string> > result;
  unsigned int i = 0;
  
  std::vector<std::string> tmp;
  while(i + n <= v.size()) {
	tmp.assign(v.begin() + i, v.begin() + i + n);
	i++;
	result.push_back(tmp);
  }

  return result;
};

int main(int argc, char *argv[]) {
  std::vector<std::string> v;
  std::vector<std::vector<std::string> > result;
  v.push_back("hoge");
  v.push_back("fuga");
  v.push_back("piyo");

  for(unsigned int i = 1; i <= v.size(); i++) {
	std::vector<std::string> tmp;
	BOOST_FOREACH(tmp, enum_cons(v, i)) {
	  result.push_back(tmp);
	}
  }

  std::vector<std::string> tmp;
  BOOST_FOREACH(tmp, result) {
	std::string s;
	BOOST_FOREACH(s, tmp) {
	  std::cout << s << " ";
	}
	std::cout << std::endl;
  }

  return 0;
}

実行結果。

/Users/syou6162% ./a.out
hoge
fuga
piyo
hoge fuga
fuga piyo
hoge fuga piyo