#include <iostream> #include <unordered_map> template <class T> void display(T c) { for(auto & e : c) std::cout<<e.first<<" "<<e.second<<std::endl; } int main(int argc, char *argv[]) { std::unordered_map<std::string, int> m; m["Buick"] = 1; m["Acura"] = 2; display(m); std::unordered_map<std::string, int> m2 = {{"Buick", 1}, {"Honda", 2}}; display(m2); std::unordered_map<std::string, int> m3; m3.insert(std::make_pair("Buick", 1)); m3.insert(std::make_pair("Honda", 2)); display(m3); return 0; }
#include <iostream> #include <unordered_map> int main(int argc, char *argv[]) { std::unordered_map<std::string, int> m; m["Buick"] = 1; m["Acura"] = 2; m["Honda"] = 3; for(int i = 0; i < m.bucket_count(); i++) { std::cout<<"Bucket "<<i<<": "; for(auto it = m.begin(i); it != m.end(i); ++it) std::cout<<"["<<it->first<<"] = "<<it->second<<" "; std::cout<<std::endl; } return 0; }
//Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { private: double width; double length; public: //constructor Rectangle(){} Rectangle(double w, double l):width(w), length(l){} //accessor double getWidth() const; double getLength() const; double getArea() const; //mutator void setWidth(double w); void setLength(double l); }; #endif //Rectangle.cpp #include "Rectangle.h" double Rectangle::getWidth() const { return width; } double Rectangle::getLength() const { return length; } double Rectangle::getArea() const { return width*length; } void Rectangle::setWidth(double w) { width = w; } void Rectangle::setLength(double l) { length = l; } //main.cpp #include <iostream> #include <functional> #include <unordered_map> #include "Rectangle.h" struct comp{ bool operator()(const Rectangle &a, const Rectangle &b) const { return (a.getArea() == b.getArea()); } }; struct RectangleHash { size_t operator()(const Rectangle &r) const { std::hash<double> h; return (h(r.getWidth()) ^ h(r.getLength())); } }; int main(int argc, char *argv[]) { std::unordered_map<Rectangle, int, RectangleHash, comp> s; s.insert(std::make_pair(Rectangle(1, 2), 1)); s.insert(std::make_pair(Rectangle(2, 3), 2)); s.insert(std::make_pair(Rectangle(3, 4), 3)); s.insert(std::make_pair(Rectangle(4, 5), 4)); std::cout<<"Size: "<<s.size()<<std::endl; for(int i = 0; i < s.bucket_count(); i++) { std::cout<<"Bucket "<<i<<": "; for(auto it = s.begin(i); it != s.end(i); ++it) std::cout<<it->first.getArea()<<"|"<<it->second<<" "; std::cout<<std::endl; } return 0; }