[英]How to remove elements from dynamically allocated array?
我有一個動態分配的數組:
myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];
我想遍歷這個數組中的所有元素並刪除那些符合我條件的元素(例如太大的矩形)。
我一直在想我可以遍歷這個數組並獲得滿足我條件的元素數量,然后分配一個新數組。 但是,如何將這些“想要的”元素“轉移”到我的新陣列中呢?
僅供記錄:我不能使用STL容器。
只需將下一個數組位置移動到需要刪除的數組上,然后將所有內容移到數組末尾。
myRectangle * lastRectanglesArray = new myRectangle[lastMaxLabel];
// initialize the entries in the lastRectanglesArray
// create a temporary array which contains info about each individual
// entry. namely, it only holds info about whether the entry should
// be kept, or deleted.
// we also use the 'entries' value, which is the number of entries
// in the new array
bool * entriesToKeep = new bool[lastMaxLabel];
int entries = 0;
// check each entry, and mark whether it should be kept or deleted
for (int i = 0; i != lastMaxLabel; ++i) {
// check whether the entry should be kept or deleted...
// here, i just put a function with signature like:
// bool shouldKeepRectangle(const myRectangle &);
entriesToKeep[i] = shouldKeepRectangle(lastRectanglesArray[i]);
if (entriesToKeep[i]) ++entries;
}
// create a new array that will contain the entries that should be kept
myRectangle * rectanglesArray = new myRectangle[entries];
// assign the entries in the new array
for (int i = 0, j = 0; i != lastMaxLabel && j != entries; ++i) {
if (entriesToKeep[i])
rectanglesArray[j++] = lastRectanglesArray[i];
}
// free the memory held by the temp array
delete [] entriesToKeep;
// if the old array is not needed anymore, delete it
delete [] lastRectanglesArray;
// and here you have rectanglesArray, a brand new array that contains
// only the elements that you need.
你看起來像使用鏈接列表的完美案例。 然而,您必須取消new myRectangle[lastMaxLabel]
部分,因為您必須將其實現為Insert()
函數的pert。
這樣,您將不需要將所需的元素轉移到新數組中,而只需刪除不需要的元素。
對用例的更多了解將有助於我們考慮更好的替代方案。
我同意Michael Chinen - 使用std :: vector代替。 你會以這種方式避免許多其他潛在的問題。 如果您確實想使用動態數組,請參閱以下問題: 刪除數組元素並移動其余元素
如果你在數組中有大量的數據,這將是使用循環移位的問題
也許你應該建立自己的數組管理類(find,add,deleteAt等)。
我的建議使用鏈接列表節點方法..它會更快,而不是你使用循環移位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.