Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle arbitrary dimensional vector in c++?

Tags:

c++

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]]

like image 431
ggrr Avatar asked Apr 23 '15 04:04

ggrr


1 Answers

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.

like image 146
Adam Avatar answered Oct 13 '22 02:10

Adam