mardi 25 juin 2019

How can we efficiently store objects using stl containers? (viz. for searching based on values of their fields)

I have objects of something like this:

struct stStudents 
{
    int roll_number;
    std::string name;
    // There could be more fields here
}

I need to store these objects using stl containers in such a way that I should be able to search them as fast as possible based on field(s) e.g roll_number or name (or both) in above example.

What I already tried/thought of:

  1. As plain as it can get, if I simply store them in std::vector (and probably by using std::find_if) searching will be O(n).

  2. With std::set and std::map it would take O(log N), but for that however overloaded comparison operator of the object needs to be based on particular field (or may be set of fields by using std::tie)

  3. Having various std::unordered_set of pointers to those objects. And define comparison operator in struct based on search criteria (just like we define multiple indices in database). This will be O(1) search but limited to predefined search criteria.

Question:

How are these approaches and what are other better alternatives can we think of?

Aucun commentaire:

Enregistrer un commentaire