Sign in to follow this  

vector size

This topic is 4389 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The "size" in the sense of number of meaningful elements is just i.size().

If you mean "size" in the sense of total bytes of memory used (including dynamic allocations owned by the vector), assuming a normal implementation you should be able to get it by sizeof(vector<int>) + sizeof(int) * i.capacity(), but I really don't know why you would ever really need to care about this value.

Share this post


Link to post
Share on other sites
Quote:
Original post by Zahlman
The "size" in the sense of number of meaningful elements is just i.size().

If you mean "size" in the sense of total bytes of memory used (including dynamic allocations owned by the vector), assuming a normal implementation you should be able to get it by sizeof(vector<int>) + sizeof(int) * i.capacity(), but I really don't know why you would ever really need to care about this value.


I just wanna konw the size of all elements in vector and I confirm if there are a method to do it . if not I must do it by i.size() * sizeof(int) .

Share this post


Link to post
Share on other sites
I'm assuming you want this for passing the data to a C-style function which wants to know the size of the data in bytes. In this case, yes, the size of the array in bytes is vector.size() * sizeof(vector::value_type).

Enigma

Share this post


Link to post
Share on other sites
That is about the only way your going to be able to do it, unless you really want to write your own vector wrapper class (I doublt you'd want to), for you'd have to write wrappers for most of the functions (unless using polymorphism?). It'd be easier just to use the previously-stated method.
 template <typename T>
class cvector : public std::vector<T> {
public:
size_t bytes() {
return size()*sizeof(T);
}
};
or
template <typename T>
class cvector {
std::vector<T> t;
public:
... //Rewrite methods (not fun)
};

EDIT:
Also, if you know how to use namespaces, I think you can use the name "vector" also.
namespace X {
... //Class stated above, name 'vector'
};
using namespace X;

Just be careful about "using namespace std;"!

Share this post


Link to post
Share on other sites

This topic is 4389 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this