Sign in to follow this  
derek7

vector size

Recommended Posts

vector<int> i; if I wanna know i size other than member number in i; I must do below: i.size() * sizeof(int) ? something convenient avaiable??

Share this post


Link to post
Share on other sites
Don't know, but as a warning- I do not believe that even what you have written there will give you an accurate size of the vector object.

Share this post


Link to post
Share on other sites
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

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