I want to create a function that 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 be [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 be [[1 2][3 4]]
The C++ template system supports recursion. You had the right idea, but you need to overload the 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 the base case. The recursive case is handled by the second function, and it should be easy to understand.
For your second example, the one that outputs [[1 2 ][3 4 ]]
, the compiler ends up generating printVector<vector<vector<int> > >()
, printVector<vector<int> >()
, and it uses the leaf printVector(int)
.
Of course you should give this function a better name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With