DEV Community

Cover image for C++ the python way
Ziga Brencic
Ziga Brencic

Posted on • Originally published at zigabrencic.com

C++ the python way

Second article in series: Intro to Modern C++

First article from Intro to Modern C++ series: here

I keep hearing. But C++ is so ugly to write. It's not like python. Sure. But the C++ community adapted, and they introduced a few cool tricks that make C++ more pythonic. To make it clear, all of the syntax mentioned here won't work in older versions of C++.

You have element based for loops in C++:

std::vector<double> x = {1, 2, 3};
for(auto &element: x){
    std::cout << element << std::endl;
}

python version would be:

x = [1, 2, 3]
for element in x:
    print(x)

Or for a map: key, value. In modern C++:

std::map<std::string, double> dict = {{"a", 2}, {"b", 4}};
for (auto const&[key, value] : dict)
    std::cout << key << " " << value << std::endl;

And in python:

dict = {"a": 2, "b": 4}
for key, value in dict.items():
    print(key + " " + value)

OK true there's nothing similar to python's enumerate in C++ but you can always do:

std::vector<double> x = {1, 2, 3};
unsigned int i = 0;
for(auto &element: x){
    std::cout << i << " " << element << std::endl;
    ++i;
}

For now that's the best implementation I came up with in C++ that is "similar" to python enumerate:

x = [1, 2, 3]
for i, element in enumerate(x):
    print( i + " " + element)

So can C++ be completely pythonic?

Itโ€™s quite interesting how the languages evolved over time. python was written with the aim to provide a simpler functionality than C++. But now python concepts are migrating into the C++ codebase. Though C++ can never replace python and python can never replace C++. But they can work really well hand in hand if we know how to leverage their strengths. Sure, in python we need to write less code then in C++. But honestly, if I have to type 10 more characters to get 15 times of code execution speed up, Iโ€™ll go with C++.

Next week Iโ€™ll show you how to bring JSON into the C++ world.

Top comments (0)