A couple Python-like features in C++11
The new C++ standard includes a couple Python-like features that I ran across recently. There are other Python-like features in the new standard, but here I’ll discuss range-based for-loops and raw strings. In Python you loop over lists rather than incrementing a loop counter variable. For example,
for p in [2, 3, 5, 7, 11]:
print pRange-based for loops now let you do something similar in C++11:
int primes[5] = {2, 3, 5, 7, 11};
for (int &p : primes)
cout << p << "n";Also, Python has raw strings. If you preface a quoted string with R, the contents of the string is interpreted literally. For example,
print "Hello\nworld"will produce
Hello
worldbut
print R"Hello\nworld"will produce
Hello\nworldbecause the `n` is no longer interpreted as a newline character but instead printed literally as two characters.
Raw strings in C++11 use R as well, but they also require a delimiter inside the quotation marks. For example,
cout << R"(Hello\nworld)";The C++ raw string syntax is a little harder to read than the Python counterpart since it requires parentheses. The advantage, however, is that such strings can contain double quotes since a double quote alone does not terminate the string. For example,
cout << R"(Hello "world")";would print
Hello "world"In Python this is unnecessary since single and double quotes are interchangeable; if you wanted double quotes inside your string, you’d use single quotes on the outside.
Note that raw strings in C++ require a capital R unlike Python that allows r or R.
The C++ features mentioned here are supported gcc 4.6.0. The MinGW version of gcc for Windows is available here. To use C++11 features in gcc, you must add the parameter -std=c++0x to the g++ command line. For example,
g++ -std=c++0x hello.cppVisual Studio 2010 supports many of the new C++ features, but not the ones discussed here.