【发布时间】:2019-11-09 19:33:45
【问题描述】:
vector::size() 给出向量中元素的数量,但我如何获得单个元素的大小?
这就是我在实践中的意思:
std::vector<char> --> 1
std::vector<int> --> 4
std::vector<double> --> 8
只有当向量至少有一个元素时,下一行才有效
int size_of_element = sizeof(myVec[0]);
如果向量中没有元素,它将不起作用。有没有直接获取类型大小的函数?
编辑:好吧,显然它确实有效。
【问题讨论】:
-
sizeof(std::vector<YourType>::value_type) -
The next line only works when the vector has at least one element If there's no elements in the vector, it won't work.不,不计算表达式,只查看它的类型。 -
sizeof(myVec[0])对于vector<bool>可能会失败。sizeof(std::vector<YourType>::value_type)是通用的。 -
在 C++11 及更高版本中,您可以使用
decltype(myVec)而不是显式拼写std::vector<YourType>:int size_of_element = sizeof(decltype(myVec)::value_type); -
如果你想从变量中获取项目的大小,那么你可以使用
sizeof(decltype(myVec)::value_type)
标签: c++ vector size std sizeof