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