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.
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 eg 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
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.)
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);
使用sizeof(vec[0])/sizeof(vec)
或sizeof(vec)/sizeof(vector<int>)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.