β¦ π 1 min, π 2 min
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 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 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 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)
Get notified & read regularly π