Problem Statement: Write a program in C++ to use map associative container. The keys will be the names of states and the values will be the populations of the states. When the program runs, the user is prompted to type the name of a state. The program then looks in the map, using the step name as an index and returns the population of the state.
Note: Scroll Horizontally to see full line of code.
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Pop
{
string name;
int population;
string s;
public:
map<string, int> state_population;
void display()
{
state_population.insert(pair<string, int>("Mahararashtra", 13));
state_population.insert(pair<string, int>("UttarPradesh", 23));
state_population.insert(pair<string, int>("Bihar", 12));
state_population.insert(pair<string, int>("WestBengal", 10));
state_population.insert(pair<string, int>("MadhyaPradesh", 9));
state_population.insert(pair<string, int>("TamilNadu", 8));
state_population.insert(pair<string, int>("Rajasthan", 8));
state_population.insert(pair<string, int>("Karnataka", 7));
state_population.insert(pair<string, int>("Gujarat", 7));
state_population.insert(pair<string, int>("AndhraPradesh", 5));
state_population.insert(pair<string, int>("Odisha", 4));
map<string, int>::iterator itr;
cout << "\nThe map State Population is : \n";
cout << "\tState\tPopulation\n";
for (itr = state_population.begin(); itr != state_population.end(); ++itr)
{
cout << '\t' << itr->first
<< '\t' << itr->second << "Cr" << endl;
}
}
void search()
{
cout << "Enter the state code : ";
cin >> s;
int val = state_population[s];
if (val == 0)
{
cout << "Invalid State!!\n";
}
else
{
cout << "Population of " << s << " is " << val << "Cr" << endl;
}
}
};
int main()
{
Pop p1;
int opt;
char con;
do
{
cout << "1.Display" << endl;
cout << "2.Search" << endl;
cout << "Enter the choice :";
cin >> opt;
switch (opt)
{
case 1:
p1.display();
break;
case 2:
p1.search();
break;
default:
cout << "Invalid";
}
cout << "To continue y :";
cin >> con;
} while (con == 'y');
cout << "Thank you";
return 0;
}
Comments
Post a Comment