Agaz Wani
Agaz Wani

Reputation: 5684

Size of array of std::vector

I would like to check the size() or number of rows in an array of std::vector().

I have vector like

std::vector<int> vec[3];

vec.size() does not work with the above vector declaration.

Upvotes: 4

Views: 14563

Answers (4)

Ramandeep Singh
Ramandeep Singh

Reputation: 558

Either use sizeof(vec[0])/sizeof(vec) or sizeof(vec)/sizeof(vector<int>)

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106068

There's nothing inherent in std::vector<int> vec[3]; to say where the first or second indexing operation constitutes "rows" vs. "columns" - it's all a matter of your own perspective as a programmer. That said, if you consider this to have 3 rows, you can retrieve that number using...

 std::extent<decltype(vec)>::value

...for which you'll need to #include <type_traits>. See here.

Anyway, std::array<> is specifically designed to provide a better, more consistent interface - and will already be familiar from std::vector:

std::array<std::vector<int>, 3> vec;
...use vec.size()...

(Consistency is particularly important if you want templated code to handle both vectors and arrays.)

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

As for why vec.size() does not work, it's because vec is not a vector, it's an array (of vectors), and arrays in C++ are not objects (in the OOP sense that they are not instances of a class) and therefore have no member functions.

If you want to get the result 3 when doing vec.size() then you either have to use e.g. std::array:

std::array<std::vector<int>, 3> vec;
std::cout << "vec.size() = " << vec.size() << '\n';  // Will output 3

Or if you don't have std::array then use a vector of vectors and set the size by calling the correct constructor:

std::vector<std::vector<int>> vec(3);
std::cout << "vec.size() = " << vec.size() << '\n';  // Will output 3

Upvotes: 11

thorsan
thorsan

Reputation: 1064

Try

int Nrows = 3;
int Ncols = 4
std::vector<std::vector<int>> vec(Nrows);
for(int k=0;k<Nrows;k++)
   vec[k].resize(Ncols);

...

auto Nrows = vec.size();
auto Ncols = (Nrows > 0 ? vec[0].size() : 0);

Upvotes: 1

Related Questions