hey,
please how can i create delete function in an array???

Dani AI

Generated

A few practical, safe options for removing an element in C++ are shown below. hinted at the in-place approach; the code samples expand that into usable functions and also show modern alternatives. As suggested, post what you tried if you need more help.

For a fixed C-style array you keep a separate logical size and shift elements down. For non-trivially-copyable types do the move-assign loop so destructors/constructors behave correctly:

#include <cstddef>

template<typename T>
void removeAt(T* arr, std::size_t& n, std::size_t index) {
    if (index >= n) return;
    for (std::size_t i = index; i + 1 < n; ++i)
        arr[i] = std::move(arr[i + 1]);
    --n; // logical size reduced; capacity unchanged
}

For trivially-copyable types you can use std::memmove for speed (careful: only for types safe to bit-copy). See std::memmove for details: std::memmove.

Prefer std::vector in most C++ code. It manages size and capacity and has convenient operations:

// remove by index
v.erase(v.begin() + index);

// remove all occurrences of value (erase-remove idiom)
v.erase(std::remove(v.begin(), v.end(), value), v.end());

See std::vector::erase and std::remove.

Extra tips: if order does not matter, replace the element with the last and pop_back() for O(1) removal. If the array holds pointers, delete the pointed objects before removing. Remember that deleting from a raw array only changes logical size; only containers like std::vector actually manage capacity and memory for you.

Recommended Answers

All 4 Replies

To delete an item from an array just move everything up one element so that the one you want to delete is overwritten. For instance, if you have an array of 10 integers and you want to delete the first one, then copy #1 to #0, #2 to #1, etc.

please can u write it in a sample program for me because i don't understand what u meant......

please can u write it in a sample program for me because i don't understand what u meant......

Yes I could. But the real question is: what don't you understand from what Ancient Dragon told you? What have you tried? Show some code and tell us what the problem is. If you're not going to put in some effort, no-one is going to help you with your problems.

And again, read the other half dozen threads on the same topic that you have started.

http://www.daniweb.com/forums/thread215686.html

commented: Yes. +30
commented: OMG, if only they put that amount of trolling effort into programming, they might actually get somewhere. +36
commented: Agree with the previous REPlies :) +22
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.