map容器使用经验点滴

来源:互联网 发布:医院网络调研报告 编辑:程序博客网 时间:2024/04/30 17:19

c++标准库里面的容器,以前用过vector,list等,
前几天在用map的时候遇到些问题。
如果在用map<key,value>的时候如果key是一个比较复杂的结构,就需要重载他所对应的
操作符'<'.
比如我们可以简单定义map<string,string>或者map<string,int>甚至
map<pair<int,int > ,string>
但是如果是
struct node{
  int start;
  int end;
  string str;
}
map<node,int>的话,因为默认的'<'操作符对于node结构没有定义,所以
需要重载这个操作符,否则虽然定义时不会出问题,但到了用的时候问题大大的。

typedef struct START_END_TRANS{
 unsigned int start;
 unsigned int end;
 string str;
}START_END_TRANS;

bool operator<(START_END_TRANS Left, START_END_TRANS Right)
   {
  

   if(Left.start < Right.start)
    return true;
   else
   {
    if((Left.start == Right.end)&&(Left.end < Right.end))
     return true;
    else
    {
     if((Left.start == Right.end)&&(Left.end == Right.end)&&(Left.str.compare(Right.str) < 0))
      return true;
     else
      return false;
    }
   }
}
经验:用map结构可以很简单地实现统计词频类似的工作
比如map<string,int>word_freq_map;
无需初始化等等,这需要
foreach word(from text)
{
   word_freq_table[word]+=1;
}
就可以得到了,是不是很简单?!!

完整具体的使用例子参看一个老外的文章。
贴在下面:

Software Design Using C++

STL: Maps

What is a Map?

The map container class provides the programmer with a convenient way to store and retrieve data pairs consisting of a key and an associated value. Each key is associated with one value. (If you want to associate a key with more than one value, look up the multimap container class.) This is similar in some ways to what we have done elsewhere in these Web pages with a list-based table and a binary search tree-based table. It is also similar to our B-tree-based table, although that was stored on disk whereas a map is stored in main memory. Another difference is that our tables were unordered; they provided no way to sequence through the data in key order. Maps are ordered, so that you can step through the data if you like.

Maps are guaranteed to be efficient. In general, inserting a new item into a map is supposed to take O(lg(n)) time, where n is the number of items in the map. However, if you want to insert at a specific location (specified by an iterator), it takes on average O(n) time. You can also sequence through the items in a map using an iterator, in ascending order by key, probably in an efficient manner as well, though this author knows of no specific time guarantee. Note, also, that we don't necessarily know what underlying data structure is used by a map.

You need to include the map header file to use maps. There are a lot of available class functions. Some of the most basic ones are outlined below. You cannot use random-access iterators with the map class, but iterators can be used to traverse a map in either ascending or descending key order.

  • empty, boolean function to report if the map is empty.
  • erase, has several forms; one of these removes the data pair having a given key.
  • find, does a search for a particular key, returning an iterator to the matching data pair.
  • insert, also has several forms, the simplest of which inserts one new data pair.
  • size, returns the number of items currently in the map.

Example

A map is ideal for storing dictionary-like data, a symbol table, etc. Our example program stores a very short dictionary of words and their meanings in a map and then allows the user to interactively look up words, in each case reporting their meanings if a match is found.

  • diction.cpp example

Although you can use key/value pairs that contain simple data items like integers and floats, this program uses objects as both the keys and the associated values. Each such object belongs to the class LineClass, which is designed to contain one "line" of text data (in this case, a word or its meaning). Note that it is necessary to provide a < operator for the class used for the keys. This is because a map is ordered according to the keys. Also, you need to provide a default constructor for the class used for the associated values.

In our example, each LineClass object contains a simple C-style string to hold the data. The default constructor places an empty string into this field (by just putting a NULL character, the character that marks the end of a C-style string, into the first location of the array of characters).

This program uses strcpy as a quick way to copy these C-style strings. Note well that strcpy does not check to see if the destination string has enough room for the data. This can open up one's software to a buffer overflow attack, a well-known type of security flaw. When writing professional software use a copy function that does proper bounds checking instead. Follow the above link for further information on this important topic.

To create an empty map that can hold pairs of such objects we use the following. Note that, unlike what was done in this example, it is legal to use a different type for the key (first item in the pair) and the value (second item in the pair).

map<LineClass, LineClass> Dictionary;

Note that the same notation is used in specifying the type for the map when passing it as a parameter to the helping functions. For example, here is the header for one of the two helping functions:

void LoadData(map<LineClass, LineClass> & Dictionary)

Inside the code for this function you see the two basic methods for creating a data pair for inserting into the map. The first one was created by using the pair constructor, with two LineClass objects as its parameters. Note the use of the LineClass constructor in each case to build an object from the C-style string supplied. In the second insertion, the make_pair generic function was used to create the pair. It, too, was handed two LineClass objects to place into the pair as the key and associated value.

Dictionary.insert(pair<LineClass, LineClass>(LineClass("hot"),   LineClass("having a high temperature")));Dictionary.insert(make_pair(LineClass("cold"),   LineClass("having a low temperature")));

The code for the Lookup function is shown below. It illustrates how to use an iterator, p, with the find class function.

map<LineClass, LineClass>::iterator p;LineType Meaning;p = Dictionary.find(LineClass(Target));if (p != Dictionary.end())   {   p->second.GetLine(Meaning);   cout << "Meaning is: " << Meaning << endl;   }else   cout << "Word not found" << endl;

Note that the find function is used to look up a key object in the map named Dictionary. This function returns an iterator to the location where the match was found or an iterator to one past the end of the data if no match was found. Since the latter is the location given by end(), one typically tests to see if the iterator equals Dictionary.end() to see if no match was found. In the case where the key was found, note that the iterator returned is an iterator to a data pair, not to the value itself. The two fields of a pair are named first and second. These are the key and value, respectively. Thus you see in the code above p->second to get at the data value in the pair pointed to by the iterator p. Since that data field is an object of class LineClass, we can in fact use the GetLine class function on this field.

As an exercise you might want to modify the above program in various ways. For one thing, the constants, types, class declaration, and function prototypes could be placed in a header file. The class functions could be placed in a separate .cpp file. You might also want to modify the program so that it reads the word and definition data from a suitable text file. That would certainly be more reasonable for a longer list of words. For example, you might want to use the text file btree.txt that was used in an earlier program. (This file might be too long to be handled; you might have to cut it down in size.)

In general, the map container class is quite convenient for the programmer. It is a lot easier to use it than to write all of the code needed for your own map-like data structure. However, should you need to have control over the details of data storage, the latter would be the appropriate choice.

The map class has additional capabilities that are not covered here. There is also a multimap container class where the keys do not have to be unique. That is, a key can be associated with more than one value. See the references for more information.

/* Filename:  diction.cpp

   Author:  Br. David Carlson

   Date:  July 14, 1999

   Last Revised:  December 23, 2001

   This interactive program creates a map (table), where each entry
   is a pair containing a word and its definition.  Thus the map is
   a small dictionary.  The program then allows the user to repeatedly
   look up the meaning of words.

   In the code, change CTRL z to CTRL d for Linux.

   Tested with:
      Microsoft Visual C++ 6.0
      Microsoft Visual C++ .NET
      g++ under Linux
*/

#include <iostream>
#include <map>

using namespace std;


const int LineMax = 72;

const int NULLCHAR = '/0';

typedef char LineType[LineMax];


/* To keep the example short, we will set up LineClass right here.
   LineClass objects each contain a short C-style string.  The idea is
   that such an object contains a line of text.  The class basically
   provides object-oriented packaging for a C-style string.
*/
class LineClass
   {
   private:
      LineType Info;
   public:
      LineClass(void);
      LineClass(LineType Str);
      void GetLine(LineType Line) const;
   };


/* Given:  Nothing.
   Task:   This is the default constructor.  It creates a LineClass object
           containing the empty string.
   Return: Nothing directly, but the implicit object is created.
*/
LineClass::LineClass(void)
   {
   Info[0] = NULLCHAR;
   }


/* Given:  Nothing.
   Task:   This constructor creates a LineClass object containing the
           string Str.
   Return: Nothing directly, but the implicit object is created.
*/
LineClass::LineClass(LineType Str)
   {
   strcpy(Info, Str);
   }


/* Given:  Nothing.
   Task:   To get the string contained in the implicit LineClass object.
   Return: Line   A copy of the string contained in the implicit object.
*/
void LineClass::GetLine(LineType Line) const
   {
   strcpy(Line, Info);
   }


/* Given:  LHS   A LineClass object (the left side of the comparison).
           RHS   A LineClass object (the right side of the comparison).
   Task:   To compare the strings containe in LHS and RHS.
   Return: In the function name, it returns true if the LHS string is less
           than the RHS string, false otherwise.
*/
bool operator<(LineClass LHS, LineClass RHS)
   {
   LineType Left, Right;

   LHS.GetLine(Left);
   RHS.GetLine(Right);

   if (strcmp(Left, Right) < 0)
      return true;
   else
      return false;
   }


// Function prototypes:
void LoadData(map<LineClass, LineClass> & Dictionary);
void Lookup(LineType Target, map<LineClass, LineClass> & Dictionary);


int main(void)
   {
   map<LineClass, LineClass> Dictionary;
   LineType Target;

   LoadData(Dictionary);

   // Change to CTRL d for Linux:
   cout << "Enter word to look for (or CTRL z to quit): ";
   cin >> Target;
   while (! cin.fail())
      {
      Lookup(Target, Dictionary);
      // Change to CTRL d for Linux:
      cout << "Enter word to look for (or CTRL z to quit): ";
      cin >> Target;
      }

   return 0;
   }


/* Given:  Target      The word to look up.
           Dictionary  The map containing the dictionary data.
   Task:   To look up Target in the Dictionary map and print the meaning
           of Target if it was found, or a "not found" message otherwise.
   Return: Nothing.
*/
void Lookup(LineType Target, map<LineClass, LineClass> & Dictionary)
   {
   map<LineClass, LineClass>::iterator p;
   LineType Meaning;

   p = Dictionary.find(LineClass(Target));
   if (p != Dictionary.end())
      {
      p->second.GetLine(Meaning);
      cout << "Meaning is: " << Meaning << endl;
      }
   else
      cout << "Word not found" << endl;
   }


/* Given:  Dictionary   A map.
   Task:   To add suitable data to Dictionary.
   Return: Dictionary   The updated map.
*/
void LoadData(map<LineClass, LineClass> & Dictionary)
   {
   // Note the 2 different ways of creating a pair to insert:
   Dictionary.insert(pair<LineClass, LineClass>(LineClass("hot"),
      LineClass("having a high temperature")));
   Dictionary.insert(make_pair(LineClass("cold"),
      LineClass("having a low temperature")));
   Dictionary.insert(make_pair(LineClass("jog"),
      LineClass("run slowly")));
   Dictionary.insert(make_pair(LineClass("intelligent"),
      LineClass("smart")));
   Dictionary.insert(make_pair(LineClass("register"),
      LineClass("a high-speed storage location on a computer's CPU chip")));
   }

原创粉丝点击