how to use a STL map?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David Loo

    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@hotmailD OTcom
    replace the DOT with a periond "." to reply by email thanks


  • Noah Roberts

    #2
    Re: how to use a STL map?

    David Loo wrote:[color=blue]
    > 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?[/color]

    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."

    Comment

    • Philippe Guglielmetti

      #3
      Re: how to use a STL map?

      "David Loo" wrote:[color=blue]
      > 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?[/color]

      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_ty pe(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


      Comment

      Working...