D
D
dansheb2014-01-21 23:37:35
C++ / C#
dansheb, 2014-01-21 23:37:35

The size of the class in the container (for example std::vector)

It would be desirable to learn the size (sizeof) of a class which is stored in the container (for example std::vector).
If the container is not empty, then this is elementary. I see a solution like this:

std::vector<int> v;
if(v.size > 0){
    std::cout << sizeof(v[0]) << std::endl;
}else{
//эта часть смущает
    v.push_back(0);
    std::cout << sizeof(v[0]) << std::endl;
    v.clear();
}

or simply
std::vector<int> v;
v.push_back(0);
std::cout << sizeof(v[0]) << std::endl;
v.pop_back();

Cons of both approaches:
1. If our class is not int and it does not have a default constructor, then it is not clear what to pass as an argument to push_back().
2. Also, if you wrap it with a class method, then this method cannot be made const, which is not logical, since the method, in theory, should not change class members.
3. Actually, we can change this v. v.capacity() may change. Of course, you can save v.capacity() before, and then restore it through v.reserve() (but that's not the point at all)
PS I ran into this problem when writing a method / function that saves an array to a binary file in the format:
size element1 element2 . .. elementN
and then reads it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zvorygin, 2014-01-21
@dansheb

Will this fit? -

typedef std::vector<int> my_container;
my_container v;
size_t size = sizeof(my_container::value_type);

Those. to be repelled not from values ​​and from type - that should be more correct.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question