tags:

views:

139

answers:

3

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?

+2  A: 

What you need is a map.

std::map<char, std::vector<YourElementClass> >
DanDan
if it's single letter: std::map<char, std::vector<YourElementClass>>even better - use simple c array with and make this letter an index.
Drakosha
Don't use char * as a key for a map. Use std::string. I don't believe pointer ordering is what you want.
Tadeusz Kopec
The pointer ordering won't be too much of a problem (unless they really care about the order it's stored in and/or attempt to sort it)... more importantly, you don't want char* because that will only be equal if *exactly the same string* (i.e. the same memory) is used as a key, rather than two strings that are equal but stored in different chunks of memory.
workmad3
Yes, these are good points. I will update the post.
DanDan
By the way, this won't compile (I think), because the compiler will misinterpret the end >>. Put a space between them ala > >. I think C++0x will correct this.
Hooked
DanDan
@Dan: Why encourage unportable practices?
Hooked
+1  A: 

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.

suszterpatt
+1  A: 

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.

Judge Maygarden