I wanted to write my own code to iterate over an n dimensional vector (where the dimension is known). Here is the code:
void printing(const auto& i, const int dimension){
int k= dimension;
for(const auto& j: i){
if(k>1){
cout<<"k: "<<k<<endl;
printing(j, --k);
}
else{
//start printing
cout<<setw(3);
cout<<j; //not quite sure about this line
}
cout<<'\n';
}
}
I get an error:
main.cpp:21:5: error: ‘begin’ was not declared in this scope
for(const auto& j: i){
^~~
Could someone help me to correct it or give me a better way to print the vector? Thanks in advance for your time.
If the dimensions are known at compile-time, this can be solved easily with a
templatethat takes dimensions as the non-type argument.The use would be, for a 2d vector:
Live Example
However, if you always know that
const auto& iwill be astd::vectortype, you can potentially solve this even easier by just not usingautoarguments at all, and instead usetemplatematching:Live Example
To compute the "dimension" of the vector, you can write a recursive type-trait for that:
Live Example
With the above recursive trait, you can get the "dimension" of each
templated vector type, without requiring the user to pass in the value at all.If you still wanted to print
k:each time, you can use the above simply with:This only works if the type is known to be a
vector-- but it could be written using concepts to work with anything following the abstract definition of something like avectoras well.If you want this to work with any range-like type, then you could replace the
vector-overload with arequires(std::ranges::range<T>)instead, and change the template-specializations for finding the dimension to also use the same. I won't pollute the answer with all this code since it's largely the same as above -- but I'll link to it in action below:Live Example