2

I am learning template programming. While doing so, I am trying to implement a template function to read n-dimensional vector.

My thought process is to recursively read through all dimensions and once I reach the innermost vector, start reading its elements. Below is the (incorrect)code that I have tried.

template<typename Container>
void read_vectors(Container c){
    read_vectors<decltype(begin(c))>(begin(c));
}

template<>
void read_vectors(vector<int> container){
    for(auto i:container)
        cout<<i<<endl;
}

int main(){
    vector<vector<vector<int>>> intvectors{{{1,2,3},{1,2,3}},{{1,2,3}, {1,2,3}}};
    read_vectors(intvectors);
    return 0;
}

Any pointers on how that can be achieved is helpful.

learning
  • 31
  • 3

1 Answers1

2

Firstly, passing function parameters by value creates a copy of the function parameter:

template<>
void read_vectors(vector<int> container){

When this is reached, a complete copy of the passed-in vector is made just for the purpose of passing in this parameter. This accomplishes absolutely nothing at all, whatsoever, except to waste memory and precious electrons. In this case, the parameters should be passed by reference.

Secondly, for all other dimensions it's also necessary to iterate over all the other dimensions too. Nothing is going to iterate over them, automatically. So the final solution is:

#include <vector>
#include <iostream>

using namespace std;

template<typename Container>
void read_vectors(const Container &c)
{
    for (const auto &i:c)
    {
        read_vectors(i);
    }
}

template<>
void read_vectors(const vector<int> &container){
    for(auto i:container)
        cout<<i<<endl;
}

int main(){
    vector<vector<vector<int>>> intvectors{{{1,2,3},{1,2,3}},{{1,2,3}, {1,2,3}}};
    read_vectors(intvectors);
    return 0;
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148