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

converting a variable name to a string in C++

You can use the preprocessor “stringify” # to do what you want: #include <stdio.h> #define PRINTER(name) printer(#name, (name)) void printer(char *name, int value) { printf(“name: %s\tvalue: %d\n”, name, value); } int main (int argc, char* argv[]) { int foo = 0; int bar = 1; PRINTER(foo); PRINTER(bar); return 0; } name: foo value: 0 name: … 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