how to handle arbitrary dimensional vector in c++? -


i want create function can handle arbitrary dimensional vector, function in psudocode:

template<class t> void printvector(vector<t> t){     if(t==vector){         printf("[");         for(auto it=t.begin(),it!=t.end();++it){             printvector(*it);         }         printf("]");     }else{         printf("%d ",t);     } } 

for example:

vector<int> a; a.push_back(12); a.push_back(34);  printvector(a); 

the output should [12 34],

vector<vector<int> > b; vector<int> b1; b1.push_back(1); b1.push_back(2); b.push_back(b1);  vector<int> b2; b2.push_back(3); b2.push_back(4); b.push_back(b2);  printvector(b); 

the output should [[1 2][3 4]]

the c++ template system supports recursion. had right idea, need overload function:

void printvector(int t) {     printf("%d ", t); }  template<class t> void printvector(std::vector<t> t) {     printf("[");     for(auto v : t){         printvector(v);     }     printf("]"); } 

the first function handles base case. recursive case handled second function, , should easy understand.

for second example, 1 outputs [[1 2 ][3 4 ]], compiler ends generating printvector<vector<vector<int> > >(), printvector<vector<int> >(), , uses leaf printvector(int).

of course should give function better name.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -