Insert method overloading

105 Views Asked by At

I am trying to overload Insert() method in C++. Here is my code which i had come up with Below is my List.h file

#ifndef _LIST_H_
#define _LIST_H__

#include "stdafx.h"
#include <cstdlib>
#include <iostream>

class List
{
public:
    List(size_t capacity = 5); // constructor - allocates dynamic array
    ~List(); // destructor

    void insert(size_t position, int value);
    void printArray();//Printing Array elements

private:
    void resize(size_t new_size); // allocate new larger array
    int *data_; // dynamic array
    size_t size_; // size of dynamic array
    size_t capacity_; // capacity of dynamic array
};

inline int& List::operator [] (size_t pos)
{
    if (pos >= 0 && pos <= size_ - 1)
    {
        return data_[pos];
    }
}
#endif _LIST_H_

This is my List.cpp file

#include "stdafx.h"
#include "List.h"
#include <iostream>
using namespace std;
List::List(size_t capacity)
{
    data_ = new int[capacity];
    capacity_ = capacity;
    size_ = 0;
}
List::~List()
{
    cout << "delete ";
    delete[] data_;
}

void List::insert(size_t position, int value) {
    if (size_ == capacity_)
    {
        resize(2 * capacity_);

    }
    if (position >= 0 && position <= capacity_ - 1)
    {
        data_[position] = value;
        size_++;
    }

}
void List::printArray()
{
    size_t  i;
    for (i = 0; i < size_; i++)
    {
        cout << data_[i]<<" ";
    }

}

void List::resize(size_t new_size)
{
    int * temp;
    size_t i;

    capacity_ = new_size;
    temp = new int[capacity_];
    for (i = 0; i <= size_; ++i)
    {
        temp[i] = data_[i];
    }
    delete[] data_;
    data_ = temp;
}

main method file

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    //List d,a;
    List *arr,*temp;
    arr = new List(10);
    temp = new List();
    arr->insert(1, 3);
    cout << "Printing array list after inserting: " << endl;
    arr->printArray();
}

Output:
Testing Insert method:

Printing array list after inserting:
-842150451


Expected:
Testing Insert method:
Printing array list after inserting:
3

suppose if i have array like arr =[1,2,3,4]; arr->insert(2,-2). Output should be arr= [1,2,-2,3,4]

Can any one tell me why it is displaying a random number instead of inserted value and How to modify the code

1

There are 1 best solutions below

0
On

You should change this line:

arr->insert(1, 3);

into:

arr->insert(0, 3);