Initialization of a Private Static Const Map in C ++
In this tutorial, we will be implementing a private static const map in C++. We will consider the example of car brands and their manufacturing country to show the implementation of this. The below implementation works fine in the GNU C++ 17 compiler and above.
Implementation
#include"bits/stdc++.h"
using namespace std;
#define int long long
// Applicable for compilers with GNU C++ 17 and above
struct cars {
public:
static const string& map(const string& st)
{
return mp.at(st);
}
static void printKeys() { // Function to access the keys and their corresponding value stored in the map
for (const auto& pair : mp) {
cout << pair.first <<": "<<pair.second<<endl;
}
}
private:
static const inline std::map<string, string> mp = { //storing keys and values in the static const map
{"Tata", "India"},
{"Mercedes", "Germany"},
{"Honda", "Japan"},
{"Ford", "United States"},
{"Lamborghini", "Italy"},
{"Leapmotor", "China"}
};
};
signed main(){
cout<<"The manufacturer country of the following car brands are: "<<endl<<endl;
cars::printKeys();
}
Output
The manufacturer country of the following car brands are:
Ford: United States Honda: Japan Lamborghini: Italy Leapmotor: China Mercedes: Germany Tata: India
In this implementation, you can see that we were able to create a private static const map and also access and print the key and values stored in the map.
Leave a Reply