Whats this 'map' header file used for?
I tried google to look up on it but ended up giving many complicated coding.
can you please give me a simple C++ programme showing the common usages of map header.
for example, how can it be of use in a hash table storing a name and phone number?
try to give me some code...
thanks
#include%26lt;map%26gt; in C++?
Here's a sample of a hash table type usage:
#include %26lt;iostream%26gt;
#include %26lt;map%26gt;
using namespace std;
int main (int argc, char* argv[]) {
char sample = '+';
/* create a lookup table for operator priorities */
map%26lt;char, unsigned int%26gt; priority;
priority['('] = 0;
priority['['] = 0;
priority['{'] = 0;
priority['*'] = 1;
priority['/'] = 1;
priority['+'] = 2;
priority['-'] = 2;
priority['!'] = 9999;
/* this prints the number 2 */
printf ("priority = %d\n", priority[sample]);
}
Reply:A map is used when you want to use a value as a key to get a definition. Other languages might call it a hash. The map template uses a symmetrical binary tree. The tree uses the less-than operator by default.
To use it as a phone book:
map%26lt;string,string%26gt; phonebook;
string name, number;
..
phonebook[name] = number;
..
map%26lt;string,string%26gt;::iterator iter = phonebook.find( name );
if (iter != phonebook.end())
cout %26lt;%26lt; name %26lt;%26lt; ":" %26lt;%26lt; iter-%26gt;second %26lt;%26lt; endl;
else
cout %26lt;%26lt; name %26lt;%26lt; ": unknown" %26lt;%26lt; endl;
Reply:Map is the STL implementation of hash tables.
Read more about it on wikipedia:
http://en.wikipedia.org/wiki/Map_%28C%2B...
Here's some code:
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
#include %26lt;map%26gt;
using namespace std;
int main()
{
cout.setf(ios::boolalpha); //make boolean variables output as "true" or "false"
map%26lt;string, bool%26gt; present;
string s;
while (cin %26gt;%26gt; s %26amp;%26amp; s != "end")
present[s] = true;
while (cin %26gt;%26gt; s %26amp;%26amp; s != "end")
cout %26lt;%26lt; s %26lt;%26lt; ' ' %26lt;%26lt; present[s] %26lt;%26lt; endl;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment