Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of array of std::vector

Tags:

c++

vector

size

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.

like image 468
Agaz Wani Avatar asked Oct 16 '25 09:10

Agaz Wani


1 Answers

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
like image 65
Some programmer dude Avatar answered Oct 18 '25 23:10

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!