user1830108
user1830108

Reputation: 193

what type of data structure i need for for a key linking to multiple paraments

for example i have a class

Class foo {
    key  &KEY;
    element 1 v1;
    element 2 v2;
    element 3 v3;
};

I want to sort/go through the iterators of the class using Key and also retrieve the Class element from 1-3. what's the best way to do this? Can I used something like

multimap <int, unsigned, string, unsigned>;
multimap < Key, element 1, element 2, element 3> m;

or something like this to achieve the function mentioned above?

Upvotes: 1

Views: 101

Answers (4)

StackHeapCollision
StackHeapCollision

Reputation: 1833

You can use multiset instead of multimap, since key is a part of your class:

class foo {
    friend bool operator < (const foo & l, const foo & r) 
    {
       return l.KEY < r.KEY;
    }

    key  &KEY;
    element 1 v1;
    element 2 v2;
    element 3 v3;
};

multiset<foo> MySet;

// Assigning values to MySet . . .

// Traversing the elements in the set:
multiset<foo>::iterator  it = MySet.begin();
for(;it != MySet.end() ; it++) {
    cout<< "element 1 = "<<it->v1<< ", element 2 = "<<it->v2<<", element 3 = "<<it->v3<<endl;
}

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57753

Here's an idea:

struct Foo_Values
{
  element1 e1;
  element2 e2;
  element3 e3;
};

struct Foo
  : public Foo_Values
{
  key Key;
};

typedef std::map<key, Foo_Values> Map_Type;

To insert into the map:

Map_Type my_map;
key some_key;
//...
Foo_Values v;
key k = some_key.Key;
v = static_cast<Foo_Values>(k); // Copy the elements.
my_map[k] = v;

Upvotes: 0

Mark B
Mark B

Reputation: 96281

Just store your foo instances in a set or multiset with a comparison operator that only compares by key. Then you can iterate normally to get them in sorted order.

Upvotes: 1

anydot
anydot

Reputation: 1539

Multimap is meant to be used when you want to have one key in map pointing to multiple values, all values of the same type.

Upvotes: 0

Related Questions