Home > Software engineering >  STL function to get all dimensions of a vector in c
STL function to get all dimensions of a vector in c

Time:10-09

I wish to know if there is any STL function in c , to get the dimensions of a vector. For example, vec = [[1, 2, 3], [4, 5, 6]] The dimensions are (2, 3)

I am aware of size() function. But the function does not return dimensions.

In the above example, vec.size() would have returned 2. To get second dimension, I would have to use vec[0].size(), which would be 3

CodePudding user response:

In C , a(n std::)vector is, by definition, 1D-vector of size() elements, which can be changed in runtime.

You can define a vector of vectors (e.g., std::vector<std::vector<int>>), but that doesn't have a constraint that the 'inner' dimensions are the same. E.g., {{1, 2, 3}, {1, 2}} is valid.

Therefore, inner dimensions are ambiguous. What you can do, if you maintain it to be the same and if you're sure that you've got elements, is to query v[0].size() as well, and so on.

CodePudding user response:

As said in lorro's answer, you likely want to find the dimensions of a std::vector<std::vector<int>>.

Finding the outer dimension is easy, since all you have to do is vec.size(). But the inner vectors can be of any length, and don't have to be the same length. Assuming you want the minimum, this is doable with STL functions.

We can use std::transform to fill a vector with the dimensions of the inner vectors, and then use std::min_element to find the smaller of those.

#include <vector>
#include <algorithm>
#include <iostream>

int main() { 
  std::vector<std::vector<int>> vec = {{1, 2}, {3, 4, 5}};

  std::vector<std::size_t> dim(vec.size());

  std::transform(vec.cbegin(), vec.cend(), dim.begin(),
                 [](auto &v) { return v.size(); });

  std::size_t min = *std::min_element(dim.cbegin(), dim.cend()); 

  std::cout << "(" << vec.size() << ", " << min << ")\n";

  return 0;
}

Output:

(2, 2)
  •  Tags:  
  • c
  • Related