Wednesday, February 12, 2014

Dynamic Array Increasing as needed in C++

Hi Guys Here I am back with another time pass activity
Many of you have heard of data structures like linked lists and binary trees. All of them have their own advantages and usefulness. So for beginners and learners like me I made up this small segment of code that can help increase your array size dynamically and only as much as needed. The Code to delete a specific entry is also very similar just try to note the index and neglect that entry when copying code to another array and definitely decrease its size as well... So all of you guys waiting for code and desperate for me to share should try to understand the logic as well and implement this differently because it is very much useless if you just copy and paste the code.
So Here it is Copy and Paste, Correct and Improve any ambiguity.

 /*----------Ali Azam Rana----------------
The Code is free to be copied and moved and distributed by anyone
Changes and improvements are welcome
*******************************************************
Contact:- aliazam.rana@gmail.com
            fb.com/ali.rana007
            +92-300-662-928-2*/


#include <iostream>
#include <string>

using namespace std;

int main()
{
    int *p1 = nullptr, *p2 = nullptr;//two pointers allocating memory as needed
    int size = 0;
    string input;//input taken into string and then converted to int better control of loops
    p1 = new int[size+1];//partial allocation for first value only
    int con = 0;//converted integers are returned here
    do//loop start
    {

        cout << "\nEnter A Number";
        cin >> input;
        if (input[0] != 'q' && input[0] != 'Q')
        {
            con = stoi(input);
        }
        
        if (size == 0)
        {
            p1[0] = con;
        }
        else
        {
            if (size == 1 || p2 == nullptr)
            {
                p2 = new int[size + 1];
                for (int i = 0; i < size; i++)
                {
                    p2[i] = p1[i];
                }
                p2[size] = con;
                delete[]p1;
                p1 = nullptr;
            }
            else
            {
                p1 = new int[size + 1];
                for (int i = 0; i < size; i++)
                {
                    p1[i] = p2[i];
                }
                p1[size] = con;
                delete[]p2;
                p2 = nullptr;
            }
            
        }
        size++;
        

    } while (input != "q" && input != "Q");
    size--;
    if (p2 == nullptr)
    {
        for (int i = 0; i < size; i++)
            cout << endl << p1[i] << endl;
    }
    else
    {
        for (int i = 0; i < size; i++)
            cout << endl << p2[i] << endl;
    }

    
    cout << endl << endl;
    
    system("pause");
    return 0;
}

No comments:

Post a Comment