Friday, October 4, 2019

Priority Queue


#include <string>
#include <map>
#include <iostream>

template <typename T>
class FakePriorityQueue
{
public:
    FakePriorityQueue()
    {
        m_list = new std::map<T, float>();
    }

    ~FakePriorityQueue()
    {
        m_list->clear();
        delete m_list;
    }

    bool Empty()
    {
        return m_list->empty();
    }

    void Enqueue(T element, float priority)
    {
        m_list->insert(std::pair<T, float>{element, priority});
    }

    T Dequeue()
    {
        if (m_list->empty())
        {
            //throw
        }
        T best = (T)m_list->begin()->first;
        float priority = m_list->at(best);

        for (auto &[candidate, val] : *m_list)
        {

            if (m_list->at(candidate) < priority)
            {
                best = candidate;
                priority = m_list->at(candidate);
            }
        }

        m_list->erase(best);
        return best;
    }

private:
    std::map<T, float> *m_list = nullptr;
};

int main()
{
    auto myXXX = FakePriorityQueue<std::string>();

    myXXX.Enqueue("B", 20.0f);
    myXXX.Enqueue("C", 30.0f);
    myXXX.Enqueue("A", 10.0f);

    while (!myXXX.Empty())
    {
        std::cout << myXXX.Dequeue() << std::endl;
    }
    std::cout << "Empty!" << std::endl;
}

////////////////////////
> .\game.exe
A
B
C
Empty!



=================================
            extract keys from a C++ map
=================================
-----------
std::vector<std::string> extract_keys(std::map<std::string, std::string> const& input_map) {
  std::vector<std::string> retval;
  for (auto const& element : input_map) {
    retval.push_back(element.first);
  }
  return retval;
}
----------
std::vector<std::string> extract_values(std::map<std::string, std::string> const& input_map) {
  std::vector<std::string> retval;
  for (auto const& element : input_map) {
    retval.push_back(element.second);
  }
  return retval;
}
----------
template<typename TK, typename TV>
std::vector<TK> extract_keys(std::map<TK, TV> const& input_map) {
  std::vector<TK> retval;
  for (auto const& element : input_map) {
    retval.push_back(element.first);
  }
  return retval;
}
----------
template<typename TK, typename TV>
std::vector<TV> extract_values(std::map<TK, TV> const& input_map) {
  std::vector<TV> retval;
  for (auto const& element : input_map) {
    retval.push_back(element.second);
  }
  return retval;
}

----------
#include <iostream>
#include <unordered_map>

template<typename K, typename V>
void print_map(std::unordered_map<K,V> const &m)
{
    for (auto const& pair: m) {
        std::cout << "{" << pair.first << ": " << pair.second << "}\n";
    }
}

int main()
{
    std::unordered_map<int, char> m =
    {
        {1, 'A'},
        {2, 'B'},
        {3, 'C'}
    };
    print_map(m);
    return 0;
}

No comments: