pair pair as key of unordered_map issue

This happens because there is no specialization for std::tr1::hash<Key> with Key = std::pair<int, int>. You must to specialize std::tr1::hash<Key> with Key = std::pair<int, int> before declaring tr1::unordered_map<Pair,bool> h;. This happens because std don’t know how to hash a pair<int, int>. Following there is a example of how to specialize std::tr1::hash<> template <> struct std::tr1::hash<std::pair<int, int> … Read more

What is the difference between using a struct with two fields and a pair?

std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don’t write them you can’t make a mistake (remember how strict weak ordering … Read more

What is C# analog of C++ std::pair?

Tuples are available since .NET4.0 and support generics: Tuple<string, int> t = new Tuple<string, int>(“Hello”, 4); In previous versions you can use System.Collections.Generic.KeyValuePair<K, V> or a solution like the following: public class Pair<T, U> { public Pair() { } public Pair(T first, U second) { this.First = first; this.Second = second; } public T First … Read more

What is the preferred/idiomatic way to insert into a map?

As of C++11, you have two major additional options. First, you can use insert() with list initialization syntax: function.insert({0, 42}); This is functionally equivalent to function.insert(std::map<int, int>::value_type(0, 42)); but much more concise and readable. As other answers have noted, this has several advantages over the other forms: The operator[] approach requires the mapped type to … Read more

How to sort elements of pairs inside vector?

You just: std::sort(v.begin(), v.end()); std::pair is lexicographically compared. On the other hand if you want to sort them with respect the second element of the std::pair then you would have to defind a custom comparator in the following manner: std::sort(v.begin(), v.end(), [](std::pair<int, std::string> const &p1, std::pair<int, std::string> const &p2) { return (p1.second == p2.second)? p1.first … Read more