Reputation: 1395
I was hoping you guys could help me flush this idea out. I want to create Sets. And I think i want to construct them like so. Have a vector of pointers like this:
vector<char*> sets;
Where the user will enter in a single letter to represent the name of the set, 'A' for instance. But then I would like 'A' to point to another container so I can add in the elements.
Is this a vector of vectors? How does 'A' point to its container?
Upvotes: 0
Views: 283
Reputation: 10562
What you need is a map.
std::map<char, std::vector<YourElementClass> >
Upvotes: 2
Reputation: 27573
You can use a vector of vectors in this case since your range of keys is limited:
vector<vector<MyType> > container(128);
Now you can access the proper container by using the entered character as the key:
MyType myTypeInstance;
char input = 'a';
container[input].push_back(myTypeInstance);
This should be faster than using a std::map (i.e. map<char, MyType>
), but requires allocation of every possible container up front. It also waste space with the non-printable characters in the range 0 to 31. The latter issue could be addressed by only allocate 96 values and subtracting 32 from the user input.
Also, depending on the complexity of the type in your inner container, it may be preferable to store pointers (or a smart pointer like boost::shared_ptr) instead of storing by value.
vector<vector<shared_ptr<MyType> > > container(96);
Note that if you do use raw pointers you must be sure to delete items as they are not reclaimed by the vector.
Upvotes: 1
Reputation: 8273
I think an std::map<char*, std::set<Type> >
would satisfy your needs (where Type is whatever you want to store in your sets).
On a side note, it's generally a bad idea to implement your own version of STL containers.
Upvotes: 1