0

I'm making an array of strings, with 100 elements. I created the array in my .h file:

const int N = 100;

typedef struct {
int size = 0;
string *list = new string[N];
} tStringList;

Then in my .cpp file, I implement the functions insert, search, remove and print for the array. But I don't know how to delete the element at the position pos of the array in the function remove. I tried this but it gives me error:

void remove(tStringList & stringList, int pos){

delete stringList.list[pos];
stringList.size--;
}

How do I delete a single element in a dynamic array?

3
  • this is not possible. new and delete in C++ ist not recommendet, use containers like std::vector. Commented Apr 28, 2017 at 8:42
  • You need to move the elements from pos + 1 till N to one previous position in the array. Commented Apr 28, 2017 at 8:43
  • I picked one of the many duplicates at random. Also see this list. Commented Apr 28, 2017 at 8:45

1 Answer 1

1

You have not to delete the element at pos, you should only move all elements after pos back with something like this:

void remove(tStringList & stringList, int pos){
    if(pos < stringList.size && pos >= 0){
        for(int i = pos; i < stringList.size - 1; i++){
            stringList.list[i] = stringList.list[i+1];
        }
        stringList.size--;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I edited the answer with size and pos check.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.