Python to C++ conversion substituting vectors for lists in a recursive function

lugal lcrees at gmail.com
Wed Mar 23 12:10:17 CET 2005


I'm new to C++, coming from a Python background. I wrote the following
code in C++ based on the Python code found here:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478

//beginning

#include <vector>
#include <iostream.h>
using namespace std;

void looper(vector <vector<int> > nseq, vector<int> comb);
vector <vector<int> > master;

int main() {
	int n, C;
	vector <vector<int> > seq;
	vector<int> holder;
	cout << "Enter constant: ";
	cin >> C;
	cout << "Enter n: ";
	cin >> n;
	for(i=0; i<=n; i++) {
		vector <int> tmp;
		for(int j=0; j<=C; j++) {
			tmp.push_back(j);
		}
		seq.push_back(tmp);
	}
	looper(seq, holder);
	return 0;
}

void looper(vector <vector<int> > nseq, vector<int> comb) {
	if(nseq.size()>0) {
		vector<int> tseq = nseq.at(0);
		for(int i=0; i<tseq.size(); i++) {
			vector <vector<int> > gseq = nseq;
			vector<int> tcomb = comb;
			gseq.erase(0);
			tcomb.push_back(tseq[i]);
			looper(gseq, tcomb);
		}
	} else {
		master.push_back(comb);
	}
}

// end

The program dies on the line:

tcomb.push_back(tseq[i]);

in the recursive function. Is my C++ translation accurate from the
original Python?




More information about the Python-list mailing list