Removing structs from assoc array while iterating over it

Matt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 16 02:16:03 PDT 2015


I am creating a simple SDL_Texture manager, and was wondering if 
the following code would work:

---
// 'list' is am assoc array of a struct containing a pointer and 
ref counter.
// max_list_length is set to 20 if it's ever found to be 0

// compact list
if(list.length == max_list_length){
	string to_remove;
	
	foreach(string st, entry; list){
		if(to_remove.length){
			list.remove(to_remove);
			to_remove = "";
		}
		if(entry.ref_count == 0){
			to_remove = st;
		}
	}
	
	if(to_remove.length){
		list.remove(to_remove);
		to_remove = "";
	}
}

---

I previously kept track of the keys of all entries found to have 
a ref_count of 0, and ran over those to remove them in a while 
loop, but was wondering if this would work, only needing to run 
over the list once. If there's a faster, cleaner way to do this, 
please do explain.

Many thanks in advance.


More information about the Digitalmars-d-learn mailing list