简体   繁体   中英

C++: Using sizeof() division to find the size of a vector

I am trying to get the size of a vector as a number so that I can use it as a constexpr .

The vector.size() returns a size type that is not a constant expression. Therefore, I thought to use sizeof(vector) / sizeof(vector[0]) to get an integer value which I can manually use in a constexpr initialization.

const vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << sizeof(int_vec) / sizeof(int_vec[0]) << endl;

My CLion compiler always prints 6. I do not understand why. Any help will be appreciated.

Thanks for the response. I learned that I can use sizeof(arr) / sizeof(arr[0]) to find the length of an array. So how would this not work for a vector?

The reason why vector.size() isn't constexpr is that std::vector grows as you add data to it; it has a variable size that is not known at compile time. (That's what constexpr means, that the value of the expression is known at compile time.)

What sizeof (vector) gets you is the size of the in-memory representation of the vector class, which has nothing to do with how many elements are stored in it. This obviously can't be correct because vector is a class name, not a variable name, so it can't possibly return the size of any one specific vector.

Using sizeof int_vec , which by the way does not require parentheses, as sizeof is an operator and not a function, is a little more rational, since at least you're asking about the size of some specific vector and not all vectors in general. But again the problem is that you're going to get the size of the in-memory representation, which has to be fixed. After all, you can instantiate one on the stack, and so it has to be of some fixed size so that C++ knows how much space to allocate for it. It can't just expand in place as you add elements to it, because it would overwrite other data on the stack. It has to have some internal pointer to dynamically-allocated memory for storing the elements. When you do sizeof int_vec you're getting the space needed for this pointer and other internal data, not the space needed for the elements themselves.

If you want an array-like container that has a size that's fixed at compile time, try std::array .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM