how to use a STL map?

D

David Loo

Hi,

I want to use a map to store a list of strings and i dont want a duplicate
string added to the list.
how can I go about this using the STL map?

Thank you.
loodav@hotmailDOTcom
replace the DOT with a periond "." to reply by email thanks
 
N

Noah Roberts

David said:
Hi,

I want to use a map to store a list of strings and i dont want a duplicate
string added to the list.
how can I go about this using the STL map?

I can't really say without knowing what you want better, but if all you
want is to keep a bunch of unique values use a set.
 
P

Philippe Guglielmetti

David Loo said:
I want to use a map to store a list of strings and i dont want a duplicate
string added to the list. how can I go about this using the STL map?

a std::map stores pairs of values, ensuring the first element of each stored
pair is unique.
so you can for example do something like:

class unique_strings: public map<string,int> // stores strings without
duplicates, int is dummy
{
typedef pair<string,int> value_type; // normally already defined in
map
// constructors...
bool insert(const string& s) {return insert(value_type(s,1)).parent;}
// map::insert returns a pair<iterator, bool> result
bool contains(const string& s) const {return find(s)!=end();} //
map::find returns an iterator to the found pair
};

Note that you can very easily use the <int> term of the pair to store a
number of occurences...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top