Below is the complete code for the main.cpp file:
C++
#include <iostream>
#include <vector>
#include <string>
#include "statepair.h"
using namespace std;
// Vectors of zip code - state abbreviation pairs, state abbreviation - state name pairs, and state name - population pairs
vector<StatePair<int, string>> zipcodestate;
vector<StatePair<string, string>> abbrevstate;
vector<StatePair<string, int>> statepopulation;
// Function to search for a state abbreviation given a zip code
string getAbbreviation(int zipCode) {
for (StatePair<int, string> pair : zipcodestate) {
if (pair.first == zipCode) {
return pair.second;
}
}
return "";
}
// Function to search for a state name given a state abbreviation
string getName(string abbrev) {
for (StatePair<string, string> pair : abbrevstate) {
if (pair.first == abbrev) {
return pair.second;
}
}
return "";
}
// Function to search for a population given a state name
int getPopulation(string stateName) {
for (StatePair<string, int> pair : statepopulation) {
if (pair.first == stateName) {
return pair.second;
}
}
return 0;
}
int main() {
// Read the zip code from the user
int zipCode;
cin >> zipCode;
// Get the state abbreviation from the vector zipcodestate
string stateAbbreviation = getAbbreviation(zipCode);
// Get the state name from the vector abbrevstate
string stateName = getName(stateAbbreviation);
// Get the population from the vector statepopulation
int population = getPopulation(stateName);
// Output the result
cout << stateName << ": " << population << endl;
return 0;
}
So, Before running the code, one need to create the statepair.h file and define the StatePair class template. Below is the code for the statepair.h file:
C++
template <class T1, class T2>
class StatePair
{
private:
T1 first;
T2 second;
public:
StatePair(T1 firstValue, T2 secondValue) : first(firstValue), second(secondValue) {}
T1 getFirst() const { return first; }
void setFirst(T1 firstValue) { first = firstValue; }
T2 getSecond() const { return second; }
void setSecond(T2 secondValue) { second = secondValue; }
void printInfo() {
cout << "(" << first << ", " << second << ")" << endl;
}
};