C++/Map Multimap/map

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Add user-defined object to map, loop through the map and output

    
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
class PC{
   public:
   enum PC_type { Dell, HP, IBM, Compaq };
   PC( PC_type appliance = Dell, int model = 220,
      int serial = 0 );
   bool operator<( const PC& rhs ) const;
   PC_type appliance() const;
   int model() const;
   string name() const;
   void print() const;
   int serial() const;
   private:
   PC_type appliance_;
   int model_;
   int serial_;
};
inline
PC::PC( PC::PC_type appliance, int model,
   int serial )
   : appliance_( appliance ), model_( model ), serial_( serial )
{} 
inline
bool PC::operator<( const PC& rhs ) const
{ return appliance() < rhs.appliance() ||
   ( appliance() == rhs.appliance() && model() < rhs.model() );
}
inline
PC::PC_type PC::appliance() const
{ return appliance_; }
inline
int PC::model() const
{ return model_; }
string PC::name() const
{
   string what;
   switch( appliance() )
   {
      case Dell:    what = "Dell";              break;
      case HP:      what = "HP";                break;
      case IBM:     what = "IBM";               break;
      case Compaq:  what = "Compaq";            break;
      default:      what = "Unknown appliance"; break;
   }
   return what;
}
inline
void PC::print() const
{
   char oldfill = cout.fill();
   cout << name() << " - Model "
        << model() << ", Serial number " 
        << serial() << endl;
}
inline
int PC::serial() const
{ return serial_; }
bool greater_model( const pair<PC::PC_type,PC> p,int min_model );
int main( )
{
   const PC::PC_type kind[] = { PC::IBM,PC::Dell,PC::HP};
   int num_appliances = 3;
   vector<PC> v;
   for( int i = 0; i < 3; ++i )
      v.push_back( PC( kind[i], i, i ) );
   map<int,PC> sold;
   transform( kind, kind+num_appliances, v.begin(),inserter( sold, sold.end() ),make_pair<int,PC> );
   map<int,PC>::const_iterator sold_end = sold.end();
   map<int,PC>::const_iterator site;
   for( site = sold.begin(); site != sold_end; ++site )
      site->second.print();
}


Computing an inner product of tuples represented as maps

  
 
#include <map>
#include <iostream>
using namespace std;
int main()
{
  const long N = 600000; // Length of tuples x and y
  const long S = 10;     // Sparseness factor
  map<long, double> x, y;
  for (long k = 0; 3 * k * S < N; ++k)
    x[3 * k * S] = 1.0;
  for (long k = 0; 5 * k * S < N; ++k)
    y[5 * k * S] = 1.0;
  double sum;
  map<long, double>::iterator ix, iy;
  for (sum = 0.0, ix = x.begin(); ix != x.end(); ++ix) {
    long i = ix->first;
    iy = y.find(i);
    if (iy != y.end())
      sum += ix->second * iy->second;
  }
  cout << sum << endl;
  return 0;
}
 /* 
4000
 */


Create string float map

  
 
/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
    /* type of the container:
     * - map: elements key/value pairs
     * - string: keys have type string
     * - float: values have type float
     */
    typedef map<string,float> StringFloatMap;
    StringFloatMap coll;
    // insert some elements into the collection
    coll["VAT"] = 0.15;
    coll["Pi"] = 3.1415;
    coll["an arbitrary number"] = 4983.223;
    coll["Null"] = 0;
    /* print all elements
     * - iterate over all elements
     * - element member first is the key
     * - element member second is the value
     */
    StringFloatMap::iterator pos;
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << "key: \"" << pos->first << "\" "
             << "value: " << pos->second << endl;
    }
}
 /* 
key: "Null" value: 0
key: "Pi" value: 3.1415
key: "VAT" value: 0.15
key: "an arbitrary number" value: 4983.22
 */


Declare a char int map

  
 
#include <iostream>
#include <map>
using namespace std;
int main()
{
  map<char, int> m;
  // put pairs into map
  for(int i=0; i<26; i++) {
    m.insert(pair<char, int>("A"+i, 65+i));
  }
  char ch = "G";
  map<char, int>::iterator p;
  
  // find value given key
  p = m.find(ch);
  if(p != m.end()) 
    cout << "Its ASCII value is  " << p->second;
  else
    cout << "Key not in map.\n";
  return 0;
}
/* 
Its ASCII value is  71
 */


Define string-string map and loop through the value key-pair

  
 
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main( ) {
   map<string, string> strMap;
   strMap["Monday"]    = "1";
   strMap["Tuesday"]   = "2";
   strMap["Wednesday"] = "3";
   strMap["Thursday"]  = "4";
   strMap["Friday"]    = "5";
   strMap["Saturday"]  = "6";
   strMap.insert(pair<string, string>("Sunday", "7"));
   for (map<string, string>::iterator p = strMap.begin( );
      p != strMap.end( ); ++p ) {
         cout << "English: " << p->first<< ", #: " << p->second << endl;
   }
   cout << endl;
}
 /* 
English: Friday, #: 5
English: Monday, #: 1
English: Saturday, #: 6
English: Sunday, #: 7
English: Thursday, #: 4
English: Tuesday, #: 2
English: Wednesday, #: 3

 */


Demonstrating an STL map

  
 
#include <iostream>
#include <map>
#include <string>
using namespace std; 
int main()
{
  map<string, long> directory;
  directory["A"] = 1234567;
  directory["B"] = 9876543;
  directory["C"] = 3459876;

  string name = "A";
  if (directory.find(name) != directory.end()) 
      cout << "The phone number for " << name
           << " is " << directory[name] << "\n";
   else
      cout << "Sorry, no listing for " << name << "\n";
  return 0;
}
 /* 
The phone number for A is 1234567
 */


Get the size of a map

  
#include <map>
#include <iostream>
#include <string>
using namespace std;
typedef map<string, int> STRING2INT;
int main(void)
{
    STRING2INT DateMap;
    STRING2INT::iterator DateIterator;
    string DateBuffer;
    DateMap["January"] = 1;
    DateMap["February"] = 2;
    DateMap["March"] = 3;
    DateMap["April"] = 4;
    DateMap["May"] = 5;
    DateMap["June"] = 6;
    DateMap["July"] = 7;
    DateMap["August"] = 8;
    DateMap["September"] = 9;
    DateMap["October"] = 10;
    DateMap["November"] = 11;
    DateMap["December"] = 12;
    if(!DateMap.empty())
        cout << "DateMap has " << DateMap.size() << " entries" << endl;
    else
        cout << "DateMap is empty" << endl;
}


Multiple map

  
 
/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
    // define multimap type as string/string dictionary
    typedef multimap<string,string> StrStrMMap;
    // create empty dictionary
    StrStrMMap dict;
    // insert some elements in random order
    dict.insert(make_pair("day","Tag"));
    dict.insert(make_pair("strange","fremd"));
    dict.insert(make_pair("car","Auto"));
    dict.insert(make_pair("smart","elegant"));
    dict.insert(make_pair("trait","Merkmal"));
    dict.insert(make_pair("strange","seltsam"));
    dict.insert(make_pair("smart","raffiniert"));
    dict.insert(make_pair("smart","klug"));
    dict.insert(make_pair("clever","raffiniert"));
    // print all elements
    StrStrMMap::iterator pos;
    cout.setf (ios::left, ios::adjustfield);
    cout << " " << setw(10) << "english "
         << "german " << endl;
    cout << setfill("-") << setw(20) << ""
         << setfill(" ") << endl;
    for (pos = dict.begin(); pos != dict.end(); ++pos) {
        cout << " " << setw(10) << pos->first.c_str()
             << pos->second << endl;
    }
    cout << endl;
    // print all values for key "smart"
    string word("smart");
    cout << word << ": " << endl;
    for (pos = dict.lower_bound(word);
         pos != dict.upper_bound(word); ++pos) {
            cout << "    " << pos->second << endl;
    }
    // print all keys for value "raffiniert"
    word = ("raffiniert");
    cout << word << ": " << endl;
    for (pos = dict.begin(); pos != dict.end(); ++pos) {
        if (pos->second == word) {
            cout << "    " << pos->first << endl;
        }
    }
}
 /* 
 english   german
--------------------
 car       Auto
 clever    raffiniert
 day       Tag
 smart     elegant
 smart     raffiniert
 smart     klug
 strange   fremd
 strange   seltsam
 trait     Merkmal
smart:
    elegant
    raffiniert
    klug
raffiniert:
    clever
    smart
 */


Put value to map with assignment

  
#include <map>
#include <iostream>
#include <string>
using namespace std;
typedef map<string, int> STRING2INT;
int main(void)
{
    STRING2INT DateMap;
    STRING2INT::iterator DateIterator;
    string DateBuffer;
    DateMap["January"] = 1;
    DateMap["February"] = 2;
    DateMap["March"] = 3;
    DateMap["April"] = 4;
    DateMap["May"] = 5;
    DateMap["June"] = 6;
    DateMap["July"] = 7;
    DateMap["August"] = 8;
    DateMap["September"] = 9;
    DateMap["October"] = 10;
    DateMap["November"] = 11;
    DateMap["December"] = 12;
    if(!DateMap.empty())
        cout << "DateMap has " << DateMap.size() << " entries" << endl;
    else
        cout << "DateMap is empty" << endl;
}


Store objects in a map

  
 
#include <iostream>
#include <map>
#include <cstring>
using namespace std;
class Name {
  char str[40];
public:
  Name() {
     strcpy(str, "");
  }
  Name(char *s) {
     strcpy(str, s);
  }
  char *get() {
     return str;
  }
};
// Must define less than relative to Name objects.
bool operator<(Name a, Name b)
{
   return strcmp(a.get(), b.get()) < 0;
}
class Number {
  char str[80];
public:
  Number() {
     strcmp(str, "");
  }
  Number(char *s) {
     strcpy(str, s);
  }
  char *get() {
     return str;
  }
};

int main()
{
  map<Name, Number> directory;
  directory.insert(pair<Name, Number>(Name("T"),Number("555-4444")));
  directory.insert(pair<Name, Number>(Name("C"),Number("555-3333")));
  directory.insert(pair<Name, Number>(Name("J"),Number("555-2222")));
  directory.insert(pair<Name, Number>(Name("R"),Number("555-1111")));
  char str[80] = "T";
  map<Name, Number>::iterator p;
  p = directory.find(Name(str));
  if(p != directory.end())
    cout << "Phone number: " <<  p->second.get();
  else
    cout << "Name not in directory.\n";
  return 0;
}
/* 
Phone number: 555-4444
 */


Use a map to create a phone directory.

  
#include <iostream>
#include <map>
#include <cstring>
using namespace std;
   
class name {
  char str[40];
public:
  name() { strcpy(str, ""); }
  name(char *s) { strcpy(str, s); }
  char *get() { return str; }
   
};
   
bool operator<(name a, name b)
{
   return strcmp(a.get(), b.get()) < 0;
}
   
class phoneNum {
  char str[80];
public:
  phoneNum() { strcmp(str, ""); }
  phoneNum(char *s) { strcpy(str, s); }
  char *get() { return str; }
};
   
   
int main()
{
  map<name, phoneNum> directory;
   
  directory.insert(pair<name, phoneNum>(name("A"), phoneNum("555-1111")));
  directory.insert(pair<name, phoneNum>(name("B"), phoneNum("555-2222")));
  directory.insert(pair<name, phoneNum>(name("C"), phoneNum("555-3333")));
  directory.insert(pair<name, phoneNum>(name("D"), phoneNum("555-4444")));
   
   
  map<name, phoneNum>::iterator p;
 
  p = directory.find(name("A"));
  if(p != directory.end())
    cout << "Phone number: " <<  p->second.get();
  else
    cout << "Name not in directory.\n";
   
  return 0;
}


Use string as the key and value in a map

  
 
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
  map<string, string> directory;
  directory.insert(pair<string, string>("T", "555-4444"));
  directory.insert(pair<string, string>("C", "555-3333"));
  directory.insert(pair<string, string>("J", "555-2222"));
  directory.insert(pair<string, string>("R", "555-1111"));
  string s = "T";
  map<string, string>::iterator p;
  p = directory.find(s);
  if(p != directory.end())
    cout << "Phone number: " << p->second;
  else
    cout << "Name not in directory.\n";
  return 0;
}
 /* 
Phone number: 555-4444
 */