vector size

Started by
4 comments, last by deadimp 18 years, 4 months ago
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??
Advertisement
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.
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.
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) .
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
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;"!
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire

This topic is closed to new replies.

Advertisement