delete[] an array of objects
Every use of new
should be balanced by a delete
, and every use of new[]
should be balanced by delete[]
.
for(int i=0;i<N;i++)
delete array[i];
delete[] array;
That would be appropriate only if you initialized the array as:
Objects **array = new Objects*[N];
for (int i = 0; i < N; i++) {
array[i] = new Object;
}
The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.
BTW, obligatory: avoid allocating arrays with new[]
; use std::vector
instead, and then its destructor will take care of cleanup for you. Additionally it will be exception-safe by not leaking memory if exceptions are thrown.
Remove Object from Array using JavaScript
You can use several methods to remove item(s) from an Array:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, someArray.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
If you want to remove element at position x
, use:
someArray.splice(x, 1);
Or
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter
, or Array.splice
combined with Array.findIndex
(see MDN).
See this Stackblitz project or the snippet below:
// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" );
log(`let noJohn = someArray.filter( el => el.name !== "John")`,
`non destructive filter [noJohn] =`, format(noJohn));
log(`**someArray.length ${someArray.length}`);
// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("",
`someArray2 = someArray2.filter( el => el.name !== "John" )`,
`destructive filter/reassign John removed [someArray2] =`,
format(someArray2));
log(`**someArray2.length after filter ${someArray2.length}`);
// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("",
`someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1),`,
`destructive splice /w findIndex Brian remains [someArray3] =`,
format(someArray3));
log(`**someArray3.length after splice ${someArray3.length}`);
// if you're not sure about the contents of your array,
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", `someArray4.splice(indx, indx >= 0 ? 1 : 0)`,
`check findIndex result first [someArray4] = (nothing is removed)`,
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);
// -- helpers --
function format(obj) {
return JSON.stringify(obj, null, " ");
}
function log(...txt) {
document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}
function getArray() {
return [ {name: "Kristian", lines: "2,5,10"},
{name: "John", lines: "1,19,26,96"},
{name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**
</pre>
How do I remove an object from an array with JavaScript?
Well splice
works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete
operator on Arrays. delete
will not remove an entry from an Array, it will simply replace it with undefined
.
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
Delete object from array in c++
delete fruits[0]
will delete that one object for you. delete[]
instead serves to delete all non-null elements of that array, but fruits[0]
is not an array of objects.
Deleting an array of objects
My first question is what happens to old object at the changed index?
An object in an array never goes anywhere. The "old" object remains in that index. You invoke the assignment operator on that object. The assignment operator modifies the object.
Does the array in it leak?
The array that the object pointed to before the assignment does leak, yes.
I thought that I need to call destructor myself to prevent memory leak
You created the object with new[]
, so you do need to call delete[]
, which indeed calls the destructors.
but it gives heap error
That's because you forgot to follow the rule of 3 (or of 5).
anArr[2]
contains the same pointer that the temporary A(2)
contained, but since the destructor of the temporary has already run, it has already deleted the array and the destructor of anArr[2]
then tries to delete it again. Which is one of the things that must not be done.
Conclusions:
- When you do manual memory management, follow the rule of 3
- Don't do manual memory management. Use
std::vector
orstd::array
here instead.
Deleting array elements in JavaScript - delete vs splice
delete
will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
Note that it is not in fact set to the value undefined
, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty
when logging the array.
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
myArray.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
In Rails, how do I delete all the objects in an array?
This code will make a single SQL query:
unused_currencies = all_currencies - currencies_from_feed
CurrencyModel.delete(unused_currencies)
where CurrencyModel
is the model of your currencies.
You might want to use destroy
if you need to run callbacks on the models:
unused_currencies = all_currencies - currencies_from_feed
CurrencyModel.destroy(unused_currencies.map(&:id))
This code will make a number of queries proportional to the number of unused currencies
Related Topics
How to Export Templated Classes from a Dll Without Explicit Specification
C++ Short-Circuiting of Booleans
Can Class Template Constructors Have a Redundant Template Parameter List in C++20
How Does _Builtin_Clear_Cache Work
Difference Between Returning Reference VS Returning Value C++
Matlab VS C++ Double Precision
Link Errors Using <Filesystem> Members in C++17
How to Truncate a File While It Is Open with Fstream
Class Type Non-Type Template Parameter Initialization Does Not Compile
Setting Vector Elements in Range-Based for Loop
At^Sysinfo and a C++ Terminal Program
Cycles in Family Tree Software
Why Use Prefixes on Member Variables in C++ Classes