简体   繁体   中英

What is the size of sizeof(vector)? C++

So the user inputs values within the for loop and the vector pushes it back, creating its own index. The problem arises in the second for loop, I think it has to do something with sizeof(v)/sizeof(vector) .

 vector<int> v;

 for (int i; cin >> i;)
 {
    v.push_back(i);
    cout << v.size() << endl;
 }

 for (int i =0; i < sizeof(v)/sizeof(vector); i++)
 {
    cout << v[i] << endl;
 }

How will I determine the size of the vector after entering values? (I'm quite new to C++ so If I have made a stupid mistake, I apologize)

Use the vector::size() method: i < v.size() .

The sizeof operator returns the size in bytes of the object or expression at compile time, which is constant for a std::vector .

http://cppreference.com is a great site to look-up member functions of STL containers.

That being said you are looking for the vector::size() member function.

for (int i = 0; i < v.size(); i++)
{
   cout << v[i] << endl;
}

If you have at your disposal a compiler that supports C++11 onwards you can use the new range based for loops :

for(auto i : v) 
{
   cout << i << endl;
}

How will I determine the size of the vector after entering values?

v.size() is the number of elements in v. Thus, another style for the second loop, which is easy to understand

for (int i=0; i<v.size(); ++i)

A different aspect of the 'size' function you might find interesting: on Ubuntu 15.10, g++ 5.2.1,

Using a 32 byte class UI224, the sizeof(UI224) reports 32 (as expected)

Note that

sizeof(std::vector<UI224>)  with    0 elements reports 24
sizeof(std::vector<UI224>)  with   10 elements reports 24
sizeof(std::vector<UI224>)  with  100 elements reports 24
sizeof(std::vector<UI224>)  with 1000 elements reports 24

Note also, that

sizeof(std::vector<uint8_t> with    0 elements reports 24 

(update)

Thus, in your line

for (int i =0; i < sizeof(v) / sizeof(vector); i++)
                   ^^^^^^^^^   ^^^^^^^^^^^^^^

the 2 values being divided are probably not what you are expecting.

A std::vector is a class. It's not the actual data, but a class that manages it.

Use std::vector.size() to get the size of the actual data.

Coliru example: http://coliru.stacked-crooked.com/a/de0bffb1f4d8c836

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM