#include #include #include #include #include class MyStr { private: std::string word; public: MyStr(const char* str) : word(str) {} // friend functions (is not a method) can access private members friend bool operator<(const MyStr& self, const MyStr& other) { return self.word.length() < other.word.length(); // compare by length } friend std::ostream& operator<<(std::ostream& out, const MyStr str) { return out << str.word; } }; int main() { std::vector numbers; int input; std::multimap mymap; // map from MyStr to int mymap.insert(std::make_pair(MyStr("apple"), 1)); mymap.insert(std::make_pair(MyStr("banana"), 2)); mymap.insert(std::make_pair(MyStr("kiwi"), 3)); mymap.insert(std::make_pair(MyStr("grapefruit"), 4)); mymap.insert(std::make_pair(MyStr("orange"), 5)); // Print the multimap content (sorted by MyStr length) for (const auto& pair : mymap) { std::cout << pair.first << " => " << pair.second << std::endl; } // Find an entry with key "orange" auto it_find = mymap.find(MyStr("orange")); if (it_find != mymap.end()) { // note that this will find "banana", which is basically the same thing as "orange"... in terms of length std::cout << "Found: " << it_find->first << " => " << it_find->second << std::endl; } else { std::cout << "Key 'orange' not found." << std::endl; } // Find all entries with keys are equal (or equivalent: we cannot decide which one is "less") to "banana" auto [start, end] = mymap.equal_range(MyStr("banana")); for (auto itr = start; itr != end; ++itr) { // This will print both "banana" and "orange" std::cout << "Found: " << itr->first << " => " << itr->second << std::endl; } auto it_baple = mymap.lower_bound(MyStr("baple")); // find first element not less than "baple" if (it_baple != mymap.end()) { std::cout << "Lower bound for 'baple': " << it_baple->first << " => " << it_baple->second << std::endl; } else { std::cout << "No lower bound found for 'baple'." << std::endl; } }