Search code examples
c++vectorstd-pairchain

How to chain delete pairs from a vector in C++?


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.


Solution

  • One (naive) solution:

    • Create a queue of items-to-delete
    • Add in your first item (user-entered)
    • While(!empty(items-to-delete)) loop through your vector
    • Every time you find your current item as the second-item in your list, add the first-item to your queue and then delete that pair

    Easy optimizations:

    • Ensure you never add an item to the queue twice (hash table/etc)