471,585 Members | 1,227 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,585 software developers and data experts.

how to use a STL map?

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
Jul 19 '05 #1
2 5366
David Loo wrote:
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.

--
Noah Roberts
- "If you are not outraged, you are not paying attention."

Jul 19 '05 #2
"David Loo" wrote:
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...
--
Philippe Guglielmetti - www.dynabits.com
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by William C. White | last post: by
2 posts views Thread by Albert Ahtenberg | last post: by
3 posts views Thread by James | last post: by
reply views Thread by Ollivier Robert | last post: by
1 post views Thread by Richard Galli | last post: by
4 posts views Thread by Albert Ahtenberg | last post: by
1 post views Thread by inderjit S Gabrie | last post: by
2 posts views Thread by Jack | last post: by
3 posts views Thread by Sandwick | last post: by
reply views Thread by Anwar ali | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.