How can I discover the size/length(in bytes) of a std::vector?

78,604

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.

Share:
78,604

Related videos on Youtube

Vahid Haratian
Author by

Vahid Haratian

a poor programmer

Updated on May 07, 2020

Comments

  • Vahid Haratian
    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
      chris over 11 years
      That'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
      Steve Jessop over 11 years
      How 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
      Lightness Races in Orbit over 11 years
      -1 for not reading the documentation.
    • bobah
      bobah over 11 years
      and &vector.front() will give you a pointer to the memory, so that you can mmap the file and memcpy the data
  • Ivaylo Strandjev
    Ivaylo Strandjev over 11 years
    You want to measure the memory size this vector requires?
  • Vahid Haratian
    Vahid Haratian over 11 years
    hey 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