std::vector 的数组大小

Size of array of std::vector

我想检查 std::vector() 数组中的 size()rows 的数量。

我有像

这样的矢量
std::vector<int> vec[3];

vec.size() 不适用于上述向量声明。

尝试

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);

至于为什么vec.size()不行,那是因为vec不是一个向量,它是一个数组(向量的),数组在C++ 不是对象(在 OOP 意义上它们不是 class 的实例)因此没有成员函数。

如果你想在执行 vec.size() 时得到结果 3 那么你要么必须使用例如std::array:

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

或者,如果您没有 std::array,则使用向量的向量并通过调用正确的 constructor:

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

std::vector<int> vec[3]; 中没有任何内容可以说明第一个或第二个索引操作构成 "rows" 与 "columns" 的位置 - 这完全取决于您作为程序员的观点。也就是说,如果您认为它有 3 行,您可以使用...

检索该数字
 std::extent<decltype(vec)>::value

...为此您需要 #include <type_traits>。参见 here

无论如何,std::array<> 专门设计用于提供更好、更一致的界面 - 并且已经从 std::vector:

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

(如果您希望模板化代码同时处理向量和数组,一致性尤为重要。)

使用 sizeof(vec[0])/sizeof(vec)sizeof(vec)/sizeof(vector<int>)