Resize () and reserve () in vector

Source: Internet
Author: User

The resize function changes the size member, and size represents the actual number of elements in the current container.

The reserve function changes the size of the capacity member, and the capacity member represents the number of containers that the container can store in total.

For example, to filter some elements of vector A to the vector B (assuming B is the newly defined vector), you can use the COPY_IF function at this time.

But the vector b space is not enough, what to do.

The reserve function should be used to change its capacity at this time.

Why not resize. In fact, resize can achieve the same effect. But the side effect of resize is to invoke the default constructor of the element type to actually construct the object to fill the vector.

Take a look at a test code:

void Testreserve ()
{
  cout << "Test Reserve" << Endl;
  Vector<mclass> VEC;
  Vec.reserve (5);
}
void Testresize ()
{
  cout << "Test Resize" << Endl;
  Vector<mclass> VEC;
  Vec.resize (5);
}
int main ()
{
  Testreserve ();
  Testresize ();
  return 0;
}

Program execution Results:


PS: (1) also works for string.

(2) The reserve member only changes the capacity of the container, but does not mean that there are actual elements stored inside. Note When you use the subscript method to access.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.