Given a std::vector
of elements of some type, how can I determine the size of the type of those elements at compile time using the Visual Studio compiler. Using sizeof
on the first element is not an option as the vector could be empty.
For clang and gcc I can do something like this:
#include <vector>
template<typename T>
size_t size_of_vector_elements(std::vector<T> vector)
{
return sizeof(T);
}
int square(int num)
{
std::vector<unsigned> vector;
return size_of_vector_elements(vector);
}
Using O2 this will be optimized at compile time to just return 4. MSVC however cannot optimize this.Is there a way to change this code to make it possible?
If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.
vector::empty() The empty() function is used to check if the vector container is empty or not.
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
Declare using std::cout and std::vector. Declare function with vector type return type which accepts vector as a variable.
In c++11 or later you can use decltype(vect)::value_type
to get type of elements in std::vector
#include <iostream>
#include <vector>
int main()
{
std::vector<double> vect;
std::cout << sizeof(decltype(vect)::value_type); // gives you sizeof(double)
return 0;
}
Since you want MSVC to generate optimized code for the square
function that is similar to what GCC generates, you will have to modify your code.
You can do away with the function template size_of_vector_elements
and make use of the fact that sizeof
does not evaluate its operand.
Then your modified square function simply becomes this:
int square(int num)
{
std::vector<unsigned> vector;
return sizeof(vector[0]);
}
The assembly that MSVC produces for this function at /O2
optimization is:
int square(int) PROC ; square, COMDAT
mov eax, 4
ret 0
int square(int) ENDP
which is similar to what GCC produces at -O2
optimization.
square(int):
mov eax, 4
ret
See godbolt demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With