In: Computer Science
d_state.h:
#ifndef STATECITY_CLASS #define STATECITY_CLASS #include #include using namespace std; // object stores the state name and city in the state class stateCity { public: stateCity (const string& name = "", const string& city = ""); // output the state and city name in the format // cityName, stateName friend ostream& operator<< (ostream& ostr, const stateCity& state; // operators < and == must be defined to use with set object. // operators use only the stateName as the key friend bool operator< (const stateCity& a, const stateCity& b); friend bool operator== (const stateCity& a, const stateCity& b); private: string stateName, cityName; }; #endif // STATECITY_CLASS
Please write in C++
Code in C++ for main.cpp (code to copy)
#include <bits/stdc++.h>
#include "d_state.h"
using namespace std;
int main(){
set<stateCity> s = {stateCity ("Virginia", "Richmond"), stateCity ("Arizona", "Phoenix"), stateCity ("New Hampshire", "Warner"), stateCity ("Kansas", "Scottsville"), stateCity ("Texas", "Longview")};
cout<<"Enter a state: ";
string state;
cin>>state;
auto it = s.find(stateCity(state));
if(it==s.end()){
cout<<state<<" is not in the set"<<endl;
}else{
cout<<*it<<endl;
}
}
code in c++ for d_state.h (code to copy)
#ifndef STATECITY_CLASS
#define STATECITY_CLASS
#include<bits/stdc++.h>
using namespace std;
// object stores the state name and city in the state
class stateCity
{
public:
stateCity (const string& name = "", const string& city = ""){
stateName=name;
cityName=city;
}
// output the state and city name in the format
// cityName, stateName
friend ostream& operator<< (ostream& ostr, const stateCity& state){
ostr<<state.cityName<<" "<<state.stateName;
}
// operators < and == must be defined to use with set object.
// operators use only the stateName as the key
friend bool operator< (const stateCity& a, const stateCity& b){
return a.stateName<b.stateName;
}
friend bool operator== (const stateCity& a, const stateCity& b){
return a.stateName==b.stateName;
}
private:
string stateName, cityName;
};
#endif // STATECITY_CLASS
Code screenshot main.cpp
Code screenshot d_state.h
Sample output screenshot 1
Sample Output screenshot 2
Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.