简体   繁体   中英

what does vector.size mean?

I wonder about this code

vector<pair<int,int>> map;

std::cout << "hello"<< std::endl;

map.push_back(make_pair(1,2));
map.push_back(make_pair(3,4));
map.push_back(make_pair(5,6));

map.resize(0);

std::cout << map[0].first
            << map[0].second << std::endl;
std::cout << map[2].first << std::endl;

std::cout << map.size() << std::endl;
std::cout << map.capacity() << std::endl;

I resize the map to size 0, but the result shows like this:

hello
12
5
0
4

Why do I get this?

Size of the vector (objects it contains) is not necessarily equal to its capacity (storage space allocated for it)

Looking at http://www.cplusplus.com/reference/vector/vector/size/ , you can notice this statement: "This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity."

If you check you can see the following: http://www.cplusplus.com/reference/vector/vector/capacity/ "This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion."

I hope this answers your question

Besides the thing about the vector capacity in the other answer, accessing out of bounds indexes on vectors with the bracket operator (instead of at() , which provides bound checking) produces undefined behavior .

In other words, the behavior is not defined in the standard and can change based on things like your compiler. In your case, it apparently did not crash and outputted the values even after they're no longer in the vector.

Needless to say, you want to make sure your program is free of undefined behavior.

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