Search⌘ K
AI Features

- Solutions

Explore solutions for using MyInt as a key in std::map by implementing ordering support with MySmaller and typedefs. Learn how to store and print ordered map elements, and understand type categorization through the getPrimaryTypeCategory function. This lesson prepares you for tag dispatching and idioms in the next topic.

Solution Review of Problem Statement 1

C++
// templatePolicyMap.cpp
#include <iostream>
#include <map>
#include <unordered_map>
struct MyInt{
explicit MyInt(int v):val(v){}
int val;
};
struct MyHash{
std::size_t operator()(MyInt m) const {
std::hash<int> hashVal;
return hashVal(m.val);
}
};
struct MyEqual{
bool operator () (const MyInt& fir, const MyInt& sec) const {
return fir.val == sec.val;
}
};
struct MySmaller{
bool operator () (const MyInt& fir, const MyInt& sec) const {
return fir.val < sec.val;
}
};
std::ostream& operator << (std::ostream& strm, const MyInt& myIn){
strm << "MyInt(" << myIn.val << ")";
return strm;
}
int main(){
std::cout << std::endl;
typedef std::unordered_map<MyInt, int, MyHash, MyEqual> MyUnorderedMap;
std::cout << "MyUnorderedMap: ";
MyUnorderedMap myMap{{MyInt(-2), -2}, {MyInt(-1), -1}, {MyInt(0), 0}, {MyInt(1), 1}};
for(auto m : myMap) std::cout << '{' << m.first << ", " << m.second << "}";
std::cout << std::endl;
typedef std::map<MyInt, int, MySmaller> MyOrderedMap;
std::cout << "MyOrderedMap: ";
MyOrderedMap myMap2{{MyInt(-2), -2}, {MyInt(-1), -1}, {MyInt(0), 0}, {MyInt(1), 1}};
for(auto m : myMap2) std::cout << '{' << m.first << ", " << m.second << "}";
std::cout << "\n\n";
}

Explanation

In order to use MyInt as a key in an std::map, MyInt has to support an ordering. ...