I have this text file where I am reading each line into a std::vector<std::pair>
,
handgun bullets
bullets ore
bombs ore
turret bullets
The first item depends on the second item. And I am writing a delete function where, when the user inputs an item name, it deletes the pair containing the item as second item. Since there is a dependency relationship, the item depending on the deleted item should also be deleted since it is no longer usable. For example, if I delete ore
, bullets
and bombs
can no longer be usable because ore
is unavailable. Consequently, handgun
and turret
should also be removed since those pairs are dependent on bullets
which is dependent on ore
i.e. indirect dependency on ore
. This chain should continue until all dependent pairs are deleted.
I tried to do this for the current example and came with the following pseudo code,
for vector_iterator_1 = vector.begin to vector.end
{
if user_input == vector_iterator_1->second
{
for vector_iterator_2 = vector.begin to vector.end
{
if vector_iterator_1->first == vector_iterator_2->second
{
delete pair_of_vector_iterator_2
}
}
delete pair_of_vector_iterator_1
}
}
Not a very good algorithm, but it explains what I intend to do. In the example, if I delete ore
, then bullets
and bombs
gets deleted too. Subsequently, pairs depending on ore
and bullets
will also be deleted (bombs
have no dependency). Since, there is only one single length chain (ore-->bullets
), there is only one nested for
loop to check for it. However, there may be zero or large number of dependencies in a single chain resulting in many or no nested for
loops. So, this is not a very practical solution. How would I do this with a chain of dependencies of variable length? Please tell me. Thank you for your patience.
P. S. : If you didn't understand my question, please let me know.
One (naive) solution:
Easy optimizations: