nothings / stb

stb single-file public domain libraries for C/C++
https://twitter.com/nothings
Other
25.77k stars 7.66k forks source link

how to hmdel in iterate hashmap? #1635

Closed peiyuefeng closed 2 months ago

peiyuefeng commented 2 months ago

in iterate hashmap, failed to delete specific items which match conditions. i cant find safe way to do it :

here is my code, the stbds_hmdel will change the array, so the iteration will happen unexpected things.

int map_len = stbds_hmlenu(ControlMap);
for (int i = 0; i < map_len; i++) {
key = ControlMap[i].key;
value = ControlMap[i].value;
if (value.drop_flag == 1 && value.drop_stop_time < now) {
stbds_hmdel(ControlMap, key);
}
}

how to safely delete some items in iterate hashmap?

nothings commented 2 months ago

you're deleting from a different hashmap than you're iterating?

anyway, don't cache stbds_hmlenu in a variable. obviously the length has to change when you delete from it.

nothings commented 2 months ago

Anyway, do you know how to delete from an array you're iterating from? Because it's exactly the same, and the code you're using doesn't even work for that.

nothings commented 2 months ago

Anyway, this is basically a solved problem if you use an interface like C++ (even though C++ doesn't actually implement this, but they could): https://www.nothings.org/computer/iterate.html

But in C, with only macros, where you're just using an indexed for loop, there's nothing I can do to make it work automatically, you have to treat it like an array iterator.

peiyuefeng commented 2 months ago

you're deleting from a different hashmap than you're iterating?

anyway, don't cache stbds_hmlenu in a variable. obviously the length has to change when you delete from it.

sorry, the code is error, so i just changed it .

just delete from same hashmap.

peiyuefeng commented 2 months ago

Anyway, do you know how to delete from an array you're iterating from? Because it's exactly the same, and the code you're using doesn't even work for that.

if i delete from an array, i will do this

for (int i =arrlenu(array)-1; i>=0; i--){ if(array[i].value == 1){ arrdel(array, i); } }

i will iterate array from max to 0 , then del the specifi item which match the condition.

nothings commented 2 months ago

Have you tried that with the hashmap?

peiyuefeng commented 2 months ago

Have you tried that with the hashmap?

you are right, just iterate from max to 0, it will resolve my problem.

why i ask so stupid question which i had resolve it already? it's my fault, thank you, and sorry for waste your time.