How can I discover the size/length(in bytes) of a std::vector?
A c++ std::vector has a method size()
which returns its size.
EDIT: as I get it now you need to compute the memory a given vector uses. You can't use sizeof for that as a vector uses dynamic memory and stores only a pointer of a dynamic array containing its elements. So my best suggestion would be to multiply the memory each element requires by the number of elements. Note this again will not work if the objects stores a pointer to some dynamically allocated objects - you will have again to compute their sizes separately.
There is no easy way to compute the memory a vector size in bytes in c++ that I know of.
Related videos on Youtube
Comments
-
Vahid Haratian almost 4 years
I have a vector and I want to write and read it to a file but it is not possible to determine the logical size of a vector using the
sizeof
operator.So what shall I do?
-
chris over 11 yearsThat's why they have a
size
function. When going through all elements, though, iterators are a more natural choice than needing to know the size. -
Steve Jessop over 11 yearsHow to write it to a file depends on the type of the elements -- first you need to know whether (and how) they can be written to file.
-
Lightness Races in Orbit over 11 years-1 for not reading the documentation.
-
bobah over 11 yearsand &vector.front() will give you a pointer to the memory, so that you can mmap the file and memcpy the data
-
-
Ivaylo Strandjev over 11 yearsYou want to measure the memory size this vector requires?
-
Vahid Haratian over 11 yearshey my vector is more complicated to get just a size of it because it is made of an object that it have made of some vectors and some string and lot's of other thing that they have the same situation, I want something like a memcopy