c++ - How to achieve a data structure like "QHash<int, Foo> bar;" where "bar[10]" returns all "Foo" belonging to keys of 10 or less? -


it not have qhash; existing data structure (ideally in qt) cleanly accomplishes task without being considered esoteric solution, because need code quite short (to fit on small playing card) , understandable. vectors, multi-hashes, lists, maps, or welcome, long considered practice.

basically, have class has integer value associated it. example:

class flowers {  public:      const int m_cost;      flowers(int cost) { m_cost = cost; } }  flowers roses{5}; flowers violets{7}; flowers tulips{9}; flowers posies{3};  /* place them in sort of datastructure. */  flowerdatastructure[4]; // returns posies flowerdatastructure[7]; // returns violets, roses, posies flowerdatastructure[roses.m_cost]; // returns roses, posies 

would perhaps support range such as,

flowerdatastructure[5 ... 11]; // returns roses, violets, tulips 

ps: int m_cost; not have const. assumed easier if was.

thanks.

how achieve data structure “qhash bar;” “bar[10]” returns “foo” belonging keys of 10 or less?

the right datastructure collection of non-unique items sorted integral value either std::multimap or std::multiset depending on how store key. according authors example above key stored data type have chosen std::multiset:

#include <set> #include <string> #include <qdebug>  struct flower { public:     const int m_cost;     const std::string m_name;      explicit flower(int cost) : m_cost(cost) {}     flower(const char* name, int cost) : m_cost(cost), m_name(name) {} };   int main() {     auto lessfunc = [](const flower& l, const flower& r) -> bool                     {return l.m_cost < r.m_cost;};      std::multiset<flower, decltype(lessfunc)> multiset(lessfunc);      multiset.emplace("roses", 5);     multiset.emplace("violets", 7);     multiset.emplace("tulips", 9);     multiset.emplace("posies", 3);      // request items equal or below 7     const auto& itend = multiset.upper_bound(flower{7});      for(auto = multiset.begin(); != itend; it++)     {         const flower& flower{*it};         qdebug() << flower.m_name.c_str() << flower.m_cost;     }      return 0; } 

enter image description here

if operator [upper_bound] desired can done have overload std::multiset (more work).


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -