How does C ++ define an array with the number of unknown elements ?, Number Array

Source: Internet
Author: User

How does C ++ define an array with the number of unknown elements ?, Number Array

1. Dynamic Memory Allocation

C ++ dynamic memory application:

Int arraySize; // defines the number of elements.

Cin> arraySize; // number of input Elements

Int * p; // pointer to an array

P = new int [arraySize]; // dynamically allocates memory.

...

Delete [] p; // finally releases the memory space

C language dynamic memory application:

Int arraySize; // defines the number of elements.

Scanf ("% d", & arraySize); // number of input Elements

Int * p; // pointer to an array

P = (int *) malloc (arraySize * sizeof (int) // dynamically allocate memory

...

Free (p); // finally releases the memory space

2. vector

Vector is the Vector provided in C ++ STL.

The vector size can be dynamically changed.

The vector can access elements through subscript

You can use push_back to add elements to the vector and change the size.

# Include

Vector MyArray;

// You can use myArray. push_back (integer); to add elements based on data requirements. // you can use subscript to access Vector elements.

Related Article

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.