I felt that I ported the Python code to C ++ 98.

Even if you can write it concisely in Python, you need to write a huge amount of template code in C ++ 98. For reference, I arranged the C ++ and Python code side by side.

In a nutshell, "Syntactic sugar and dynamic typing are great."

(Because it is about to be written, there may be more items in the future)

Part 1 Static / Dynamic Typing

Point get_distance(const Point& point1, const Point& point2) {
  return sqrt( pow(point1.x - point2.x, 2) + pow(point1.y - point2.y, 2);
}
def get_distance(point1, point2):
  pt1_x, pt1_y = point1
  pt2_x, pt2_y = point2
  return math.sqrt((pt1_x - pt2_x) ** 2, (pt1_y - pt2_y) ** 2)

C ++: In addition to types, modifiers such as const, *, &, and templates are annoying. (I / O is specified, and syntax check at compile time is helpful, but ...) Python: Dynamically typed, no type definition required. The type has a value, not a variable.

Part 2 List and dictionary

vector<double> calculate(const vector<Line>& lines) {
  vector<double> result;
  vector<Line>::const_iterator ite = lines.begin();
  while( ite != lines.end() ) {
    double value =Do something(*ite);
    result.push_back(value);
    ++ite;
  }
  return result;
}
def calculate(lines):
  result = [] // []In list format, {}Then the dictionary.
  for line in lines:
    value =Do something(line)
    result.append(value)
  return result

C ++: In C ++ 98, there is no syntactic sugar (C ++ 11 has syntactic sugar).

python: Object creation, element access, syntax sugar in loops. The above case can be described more concisely using list comprehensions.

def calculate(lines):
  result = [Do something(line) for line in lines]
  return result

Part 3 tuple


void foo() {
  Point pt1(0,1);
  Point pt2(0,5);
  Line line(pt1, pt2);

  double score;
  double distance;
  calculate(line, &score, &distance); 
  ...
}

void calculate(const Line& line, double* out_score, double* out_distance) {
  *out_distance = get_distance(line.point1, line.point2);
  *out_score = get_score(line);
}

double get_distance(const Point& pt1, const Point& pt2) {...}


def foo():
  pt1 = (0,1)
  pt2 = (0,5)
  line = (pt1, pt2)
  distance, score = caclculate(line)
  ...

def calculate(line):
  distance = get_distance(*line)
  score = get_score(line)
  return distance, score

def get_distance(pt1, pt2):
  ...

C ++: If you want to group values, you need to use a generic pair or define a struct / class like Point or Line. This is also a trade-off with syntax checking.

Python: Tuples come in handy when you want to pass a small pair as an argument. Overuse will reduce readability.

Part 4 Lambda expression

void foo(const Line& line, double x) {
  double y1 = func(line, x);
  double y2 = func(line, x+1);
}

//Find the y coordinate corresponding to x on the straight line.
// ※:y=1 or x=Do not consider lines such as 0.
double func(const Line& line, double x) {
   //Get tilt
   double slope = get_slope(line.point1, line.point2);
   double const_value = get_const_value(line.point1, slope);
   double y = x * slope + c;
   return y;
}

def foo(line, x):
  func = get_func(line)
  y1 = func(x)
  y2 = func(x + 1)

def get_func(line):
  slope = get_slope(*line)
  const_value = get_const_value(line[0], slope)
  return (lamda x: x * slope + c)

Lambda expressions are provided in python, so you can easily write small things. In C ++, writing a class improves reusability, but the threshold for writing is high.

Part 5 Function call

You can easily expand tuples and lists into individual arguments, or create named arguments.

Example: Reduce C ++ function overloads.

doule get_distance(const Point& pt1, const Point pt2) {
   return //Calculation result
}

double get_distance(const Line& line) {
  return get_distance(line.point1, line.point2);
}
def get_distance(point1, point2):
  return ...

def foo(line):
  get_distance(*line) //If line is a tuple or sequence, point1 automatically,Expand to point2.

Recommended Posts

I felt that I ported the Python code to C ++ 98.
I want to make C ++ code from Python code!
mong --I tried porting the code that randomly generates Docker container names to Python -
[Introduction to Python] I compared the naming conventions of C # and Python.
I wrote the code to write the code of Brainf * ck in python
I tried to get the authentication code of Qiita API with Python.
How to use the C library in Python
[Python] I will upload the FTP to the FTP server.
I want to display the progress in Python!
Rewrite Python2 code to Python3 (2to3)
python I don't know how to get the printer name that I usually use.
I stumbled on the character code when converting CSV to JSON in Python
I tried using the Python library "pykakasi" that can convert kanji to romaji.
I tried to refactor the code of Python beginner (junior high school student)
I want to write in Python! (1) Code format check
I tried to graph the packages installed in Python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
I wanted to use the Python library from MATLAB
I want to inherit to the back with python dataclass
[Python] I tried to graph the top 10 eyeshadow rankings
I want to write in Python! (3) Utilize the mock
[Python] pandas Code that is likely to be reused
A memo that I touched the Datastore with python
I tried to solve the problem with Python Vol.1
I made an action to automatically format python code
I want to use the R dataset in python
I tried to summarize the string operations of Python
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
I tried Python C extension
Convert python 3.x code to python 2.x
I downloaded the python source
I tried to find the entropy of the image with python
I want to initialize if the value is empty (python)
I tried porting the code written for TensorFlow to Theano
[Python] I started Poetry & Impression that I moved from Pipenv to poetry
I tried to simulate how the infection spreads with Python
maya Python I want to fix the baked animation again.
What I did to welcome the Python2 EOL with confidence
I tried to summarize the code often used in Pandas
I tried to illustrate the time and time in C language
[Python] I tried to visualize the follow relationship of Twitter
I didn't know how to use the [python] for statement
I just wrote the original material for the python sample code
The story that Python stopped working with VS Code (Windows 10)
Miscellaneous notes that I tried using python for the matter
I want to know the features of Python and pip
I tried to enumerate the differences between java and python
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
I want to map the EDINET code and securities number
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I want to be able to run Python in VS Code
I tried to divide the file into folders with Python
[Python3] List of sites that I referred to when I started Python
Pass OpenCV data from the original C ++ library to Python
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
I tried to make a generator that generates a C # container class from CSV with Python
I tried to remodel the code of Python beginner (junior high school student) into object-oriented crunchy
The story that the version of python 3.7.7 was not adapted to Heroku
Leave the troublesome processing to Python
I tried to solve the ant book beginner's edition with python