Hatena::Grouptopcoder

naoya_t@topcoder RSSフィード

2009-05-20

Abusing C++ Extensions for Fun and Profit

| 02:41 | Abusing C++ Extensions for Fun and Profit - naoya_t@topcoder を含むブックマーク はてなブックマーク - Abusing C++ Extensions for Fun and Profit - naoya_t@topcoder Abusing C++ Extensions for Fun and Profit - naoya_t@topcoder のブックマークコメント

http://www.topcoder.com/tc?module=Static&d1=features&d2=022006

Compound literals

I often define a small struct that will hold two or three items, such as the end-points and weight of an edge in a graph. For two-item structs there is already the utility pair template, but it has unfriendly field names (first and second compared to, say, target and cost), and it doesn't generalise well to more than two elements (although you can create a pair<pair<R, S>, T> if you really insist).


One advantage of pair that you lose when you do this is the make_pair function that creates pairs on the fly. You could of course define such a function for your class, or give it a constructor, but this can take vital coding time. GCC provides another alternative, which comes from C99: the compound literal. A compound literal is a mix between a cast and an initialiser. To understand what I mean, consider a struct defined as

struct edge
{
    int target;
    int cost;
};

An example of a compound literal is (edge) { t, c } where t and c are expressions. The values in the braces are used to initialise the values of the struct, in the order in which they are declared. This is useful for instantiating structs on-the-fly to pass to STL methods.

Comparisons

Although the header <algorithm> provides min and max functions, these have some limitations. They have only one template parameter, which specifies the type for both arguments; this sometimes leads to errors when the given arguments are of different types. GCC provides the highly non-standard operators ? (max), which will coerce the arguments to a suitable type.


These operators are most commonly seen in their assignment forms ?=. For example, the following loop computes the minimum value of a function over a range:

int m = INT_MAX;
for (int i = 0; i < N; i++)
    m <?= func(i);

これは見たことある

トラックバック - https://topcoder-g-hatena-ne-jp.jag-icpc.org/n4_t/20090520