zoukankan      html  css  js  c++  java
  • 多维容器按列组合元素

    <pre name="code" class="cpp">// alg2.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    
    //昨天碰到一个文件,有这么一个std::vector<std::vector<std::string>> 
    //如今须要将每一列的数据进行组合
    //依照普通写法,每一个vector的长度是知道的直接
    //for(int lvl1;.....)
    // for(int lvl2;...)
    //	for(int lvl3,...)
    //但问题是第一层的长度是变长,所以无法依照vector写出。

    //木有办法啊。代码还是要写,还是要将结果组合出来 //通过递归来完毕操作。 //made by davidsu33 2014-6-25 #include <boost/config/warning_disable.hpp> #include <vector> #include <string> #include <iostream> #include <assert.h> //解法1,递归 void get_combine(std::vector<std::vector<std::string>>& src, std::vector<std::string>& result, std::vector<int> & index) { assert(index.size() == src.size()); std::string aline; for (int i=0; i<index.size(); ++i) { aline += src[i][index[i]]; if (i != index.size()-1) { aline += "-"; } } result.push_back(aline); //索引进行转动移位 ++index[index.size()-1]; //const int lastColSize = src[index.size()-1].size(); for (int i=index.size()-1; i>=0; --i) { if (0 == index[i] % src[i].size()) { if (i == 0) { return; //达到上限,无法移动 } index[i] = 0; ++index[i-1]; //进位 } else { break; //继续处理 } } get_combine(src, result, index); } int _tmain(int argc, _TCHAR* argv[]) { std::vector<std::string> v1, v2; v1.push_back("aa"); v1.push_back("bb"); v1.push_back("cc"); v1.push_back("dd"); v2.push_back("ee"); v2.push_back("gg"); v2.push_back("ff"); v2.push_back("hh"); std::vector<std::vector<std::string>> v; v.push_back(v1); v.push_back(v2); //std::vector<std::vector...中存的索引 //相似password表0001 0002,初始化为0000,然后 //最低位达到该组的最大则上一位进一 std::vector<int> index(v.size(), 0); std::vector<std::string> result; get_combine(v, result, index); //---组合结果输出----- for (int i=0; i<result.size(); ++i) { std::cout<<result[i]<<std::endl; } //解决方式2,while循环 std::vector<std::string> result2; for (int i=0; i<index.size(); ++i) { index[i] = 0; } bool bExit = false; //const int lastColSize = v[v.size()-1].size(); while (true) { std::string aline; for (int i=0; i<index.size(); ++i) { aline += v[i][index[i]]; if (i != index.size()-1) { aline += "-"; } } result2.push_back(aline); ++index[index.size()-1]; for (int i=index.size()-1; i>=0; --i) { if (0 == index[i] % v[i].size()) { if (i == 0) { bExit = true; break; //达到上限。无法移动 } index[i] = 0; ++index[i-1]; //进位 } else { break; //继续处理 } } if (bExit) { break; } } getchar(); return 0; }



    
       
    
  • 相关阅读:
    bzoj 1232 [Usaco2008Nov]安慰奶牛cheer
    bzoj 1237 [SCOI2008]配对 贪心+dp
    缺8数
    缺8数
    Binary GCD algorithm
    Binary GCD algorithm
    HDU1576 A/B (解法二)【试探法】
    HDU1576 A/B (解法二)【试探法】
    I00002 打印九九乘法表
    I00002 打印九九乘法表
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7097164.html
Copyright © 2011-2022 走看看