DEV Community

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

Posted on • Originally published at zigabrencic.com

2 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay