Some Python'o-like functions in C ++ 11

From me personally:
C ++ 11 brought nothing particularly significant to the language. Roughly speaking, I simply simplified some points. Indeed, the flexibility of C ++ allows you to do everything (almost everything: it does not vacuum). But nevertheless, you must admit it is pleasant when one of the not the easiest programming languages ​​becomes more accessible for understanding, easier for perception, more convenient for work.

Translation of the text under the cut. Posted by John D. Cook.

The new C ++ standard (i.e. C ++ 11) contains a few Python-like functions that I have come across lately. This article will deal directly with for-loops and raw strings.

In Python, you can go through the list without any loop counter. For instance:
    for p in [2, 3, 5, 7, 11]:
        print p

Something similar can be used in C ++ 11:
    int primes[5] = {2, 3, 5, 7, 11};
    for (int &p : primes)
        cout << p << "\n";

Python also has a raw string. If you add the letter R before the string, the string is interpreted character by character. For example code:
    print "Hello\nworld"

Will give the following result:
Hello
world


But:
print R"Hello\nworld"

Output:
Hello \ nworld

Because \ n is not perceived as a newline, but simply displayed as two separate characters.

In C ++ 11, raw strings are used the same way, but they also require a separator inside quotes:
    cout << R"(Hello\nworld)";

The raw string syntax in C ++ 11 is a little harder to read than its Python counterpart. The advantage, however, is that such strings can contain double quotation marks; they themselves do not break the string. For instance:
    cout << R"(Hello "world")"; //здесь хабр немного не правильно подсвечивает синтаксис

Output:
Hello “world”

In Python, this is not necessary, since single and double quotes are interchangeable. To get double quotes inside a string, you need to use single quotes outside and vice versa. Also note that the raw string in C ++ 11 requires a capital R, unlike Python, in which you can use both large and small.

C ++ 11 features are supported by gcc 4.6.0. MinGW version of gcc for Windows can be downloaded here . To use C ++ 11 functions, you need to add the following parameter to the command line -std = c ++ 0x .
For example:
g ++ -std = c ++ 0x hello.cpp

Visual Studio 2010 supports a lot of the new C ++ 11 features, but alas, they are not described here.

Also popular now: