C + + Application two-dimensional array

Source: Internet
Author: User

Turn from:

There is a two-dimensional array called New in the C + + programming language, which is more flexible to use, and there are several ways to help us implement certain functions. Here we will summarize several C + + two-dimensional array new application methods, to conduct a review.

C + + two-dimensional array new application method one:

    1. A (*GA) [n] = new A[m][n];
    2. ...
    3. delete []ga;

Disadvantage: n must be a known

Advantages: Call intuitive, continuous storage, program concise (after testing, destructors can be called correctly)

C + + two-dimensional array new application method two:

    1. a** ga = new a*[m];
    2. for (int i = 0; I < m; i++)
    3. Ga[i] = new A[n];
    4. ...
    5. for (int i = 0; I < m; i++)
    6. delete []ga[i];
    7. delete []ga;

Cons: Non-sequential storage, cumbersome procedures, GA for a** type

Pros: Call intuitive, n may not be known

C + + two-dimensional array new application method three:

    1. * GA = new a[m*n];
    2. ...
    3. delete []ga;

Cons: Call not intuitive

Advantage: Continuous storage, n may not be known

C + + two-dimensional array new application Mode four:

    1. Vector > ga;
    2. Ga.resize (m); These three lines can be used
    3. for (int i = 1; I < n; i++)//
    4. Ga[i].resize (n); //
    5. ...

Disadvantages: Non-continuous storage, debugging is not convenient, the compiler speed down, program expansion (actual speed difference is not small)

Advantages: Call intuitive, automatic destruction and free memory, you can call the STL-related functions, dynamic growth

C + + two-dimensional array new application Mode five:

    1. Vector ga;
    2. Ga.resize (M*n);

The combination of method 3,4

C + + two-dimensional array new application Method VI:

Improved version of 2

    1. a** ga = new a*[m];
    2. Ga[0] = new A[m*n];
    3. for (int i = 1; I < m; i++)
    4. Ga[i] = ga[i-1]+n;

C + + Application two-dimensional array

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.