max_size, capacity and size 的区别

  The max_size() function returns the maximum number of elements that the container can hold. The max_size() function should not be confused with the size or capacity functions, which return the number of elements currently in the container and the the number of elements that the container will be able to hold before more memory will have to be allocated, respectively.

  vector 存在预分配机制。可以在元素不存在的情况下预分配一段空间,为以后的存储做准备。这段空间可以用reserve()调节。capacity()返回的值就是可以存放元素的个数。capacity() - size()就是下次重新进行空间分配前的预留元素个数。至于max_size()指的是一个vector结构可供储存元素的个数的上线,通常是由于寻址空间决定的。

  参考链接:http://www.cnblogs.com/SelaSelah/archive/2012/05/30/2526736.html

原文地址:https://www.cnblogs.com/followyourdream/p/3292097.html