C++ quick guide for Python user

Tweet


main function

Python

def main():
    print('Python program')
if __name__ == '__main__':
    main()

Output

Python program

Executed in order from top to bottom
In this case, the if statement is executed and the main function is called

C++

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
    cout << "C++ program" << endl;
    cin.get();
    return 0;
}

Output

C++ program

Executed from the main function
The reason why the cin.get function is called is so that the program will exit when the Enter key is pressed, and if you want to exit immediately, you do not need to call the cin.get function.


Comment

Python

def main():
    ''' comment line 1
    comment line 2 '''
    print('Python program') # comment
if __name__=='__main__':
    main()

Output

Python program

Comments between '''and'''
# and onwards to the end of the line is the comment

C++

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
    /* comment line 1
    comment line 2 */
    cout << "C++ program" << endl; // comment
    cin.get();
    return 0;
}

Output

C++ program

Anything between /* and */ is a comment
// and onwards to the end of the line is the comment


Semicolon

Python

def main():
    print('Line1')
    print('Line2'); print('Line3')
    print(\
        'Line4'\
            )
if __name__=='__main__':
    main()

Output

Line1
Line2
Line3
Line4

One instruction per line
Separate multiple instructions on a single line with a semicolon.
Backslash at the end of a line when writing an instruction that crosses lines

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << "Line1" << endl;
    cout << "Line2" << endl; cout << "Line3" << endl;
    cout
        << "Line4"
        << endl;
    cin.get();
    return 0;
}

Output

Line1
Line2
Line3
Line4

Separate imperatives with a semicolon.
In any case, multiple instructions on one line or across lines, each instruction up to a semi-colon is a single instruction.


Console output and line breaks

Python

def main():
    print('Mc',end='')
    print('Donald')
    print()
    print('Line1\nLine2')
    print(2,'by',3,'is',2*3)
if __name__=='__main__':
    main()

Output

McDonald

Line1
Line2
2 by 3 is 6

Use the print function to output text to the console (command prompt, terminal (terminal), etc.)
The print function outputs a character and breaks line
If you do not want a line break, specify '' for end.
\n denotes a line break

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << "Mc";
    cout << "Donald" << endl;
    cout << endl;
    cout << "Line1\nLine2\n";
    cout << 2 << " by " << 3 << " is " << 2 * 3 << endl;
    cin.get();
    return 0;
}

Output

McDonald

Line1
Line2
2 by 3 is 6

To output text to the console (command prompt, terminal (terminal), etc.), use the stream operator << to stream text into cout
Filling endl into cout will break the line.
\n denotes a line break


raw string literal

Python

def main():
    print('directory\\file')
    print(r'directory\file')
if __name__=='__main__':
    main()

Output

directory\file
directory\file

\\ represents \
The r string can write \ as it is

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << "directory\\file" << endl;
    cout << R"(directory\file)" << endl;
    cin.get();
    return 0;
}

Output

directory\file
director\file

\\ represents \
In the range enclosed by () in the R string, you can write \ as it is.


Loading Libraries

Python

import numpy as np
def main():
    print(np.random.randint(0,10))
if __name__=='__main__':
    main()

Output

1

Load libraries with import
In this case, np in np.random represents the numpy library, and random is contained in that library

C++

#include <iostream>
#include <random>
int main(int argc, char** argv)
{
    std::random_device seed;
    std::mt19937 srand(seed());
    std::uniform_int_distribution<> rand(0, 9);
    std::cout << rand(srand) << std::endl;
    std::cin.get();
    return 0;
}

Output

6

Load libraries with #include
In this case, std in std::mt19937 represents the C++ standard library, and mt19937 is contained in that library


Omission of namespace

Python

from numpy.random import randint
def main():
    print(randint(0,10))
if __name__=='__main__':
    main()

Output

9

If you want to omit writing the namespace numpy, use from to import
In this case, the randint function can be called without np.random.

C++

#include <iostream>
#include <random>
using namespace std;
int main(int argc, char** argv)
{
    random_device seed;
    mt19937 srand(seed());
    uniform_int_distribution<> rand(0, 9);
    cout << rand(srand) << endl;
    cin.get();
    return 0;
}

Output

9

If you want to omit writing the namespace std, use namespace using
In this case, the mt19937 class can be used without adding std::.


Random number

Python

import random
import numpy as np
def main():
    for _ in range(0,100):
        print(random.randint(0,9), '', end='')
    print()
    for _ in range(0,100):
        print(np.random.randint(0,10), '', end='')
if __name__=='__main__':
    main()

Output

7 9 4 9 4 1 8 0 9 0 4 7 4 3 0 0 6 1 0 4 1 7 9 2 0 6 5 6 9 8 2 0 0 9 9 3 5 2 2 8 1 0 1 1 8 7 6 8 5 1 6 6 3 3 7 2 0 7 9 9 2 9 9 0 5 7 7 6 0 1 4 6 6 5 7 3 4 8 4 4 2 0 0 3 2 0 3 3 0 6 2 3 5 4 4 6 0 7 1 7
6 8 8 1 1 0 3 7 7 0 0 8 8 9 0 8 2 2 1 5 4 2 1 9 2 8 3 3 8 0 4 2 9 4 6 6 1 6 4 3 7 7 7 9 9 0 8 4 6 7 1 4 6 1 7 8 5 4 8 6 8 5 6 4 1 5 2 0 0 1 9 2 0 5 1 6 8 2 5 2 8 1 8 8 1 9 5 8 8 5 9 7 8 9 1 8 5 8 4 7

Different value each time it is run.
Note that random's randint and numpy's randint have different ways of specifying ranges.

C++

#include <iostream>
#include <random>
using namespace std;
int main(int argc, char** argv)
{
    random_device srand;
    mt19937 next(srand());
    uniform_int_distribution<> rand(0, 9);
    for (int i = 0; i < 100; i++)
        cout << rand(next) << " ";
    cout << endl;
    cin.get();
    return 0;
}

Output

5 2 7 6 2 2 2 9 7 8 0 4 2 3 9 7 0 1 1 0 3 9 9 2 3 1 0 3 6 0 2 0 9 9 0 3 8 2 1 2 3 3 8 2 3 3 0 7 4 6 8 1 5 1 0 5 6 6 5 9 4 8 1 6 4 5 9 3 0 5 8 8 8 4 7 6 3 1 8 0 7 8 7 7 7 2 2 0 8 6 0 3 0 0 2 5 4 0 6 0

random_device has a different value each time it is run, so use it as a random number seed
I recommend using mt19937 as a random number generator.


command line argument

Python

import sys
def main():
    print(sys.argv[1])
if __name__=='__main__':
    main()

Output

option

Command

python.exe myprogram.py option

When executing a program on a console (command prompt, terminal, etc.), command line arguments can be set, which can be obtained with argv.
argv[0] is the program name
Arguments after argv[1]

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << argv[1] << endl;
    cin.get();
    return 0;
}

Output

option

Command

MyProgram.exe option

When executing a program on a console (command prompt, terminal, etc.), command line arguments can be set, which can be obtained with argv.
argv[0] is the program name
Arguments after argv[1]
Incidentally, when a file is dragged and dropped into the exe file, the file name is entered in argv.
Note that the number of arguments is the same as the number of arguments in argc


Data Type and Variable Definitions

Python

def main():
    a=200
    b=1000
    c=2.5
    d=2.5
    e='@'
    f='abc'
    g='xyz'
    h=True
    print(a,type(a))
    print(b,type(b))
    print(c,type(c))
    print(d,type(d))
    print(e,type(e))
    print(f,type(f))
    print(g,type(g))
    print(h,type(h))
if __name__=='__main__':
    main()

Output

200 <class 'int'>
1000 <class 'int'>
2.5 <class 'float'>
2.5 <class 'float'>
@ <class 'str'>
abc <class 'str'>
xyz <class 'str'>
True <class 'bool'>

No need to write the data type when defining variables
Implement with proper awareness of data types.
The type int is a type of integer, and there is no limit to the number that can be represented.
The float type is a floating-point number type, 64 bits (although not strictly 64 bits).
type str is a string type
bool type is a boolean type

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    unsigned char a = 200;
    int b = 1000;
    float c = 2.5f;
    double d = 2.5;
    char e = '@';
    char f[4] = "abc";
    string g = "xyz";
    bool h = true;
    cout << (int)a << " " << typeid(a).name() << " " << sizeof(a) << endl;
    cout << b << " " << typeid(b).name() << " " << sizeof(b) << endl;
    cout << c << " " << typeid(c).name() << " " << sizeof(c) << endl;
    cout << d << " " << typeid(d).name() << " " << sizeof(d) << endl;
    cout << e << " " << typeid(e).name() << " " << sizeof(e) << endl;
    cout << f << " " << typeid(f).name() << " " << sizeof(f) << endl;
    cout << g << " " << typeid(g).name() << " " << sizeof(g) << endl;
    cout << h << " " << typeid(h).name() << " " << sizeof(h) << endl;
    cin.get();
    return 0;
}

Output

200 unsigned char 1
1000 int 4
2.5 float 4
2.5 double 8
@ char 1
abc char [4] 4
xyz class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > 40
1 bool 1

When defining a variable, the data type must be written
Implement with proper awareness of data types.
char is an integer type, 8 bits
    (signed) char is -128 to +127
    0 to 255 for unsigned char
    unsigned is unsigned, signed if omitted
The type int is an integer type, 32-bit (though not strictly 32-bit).
The float type is a floating-point number type, 32-bit
The double type is a floating-point number type, 64-bit
The char type is a single-character type, and characters are represented by single quotation marks.
Arrays of type char are of type string, where strings are denoted by double quotation marks
    Memory (number of array elements) of the size of the number of characters + 1 must be reserved.
The type string is a string type
bool type is a boolean type


bit operation

Python

def main():
    print(1|2|4|8|16|32|64|128)
if __name__=='__main__':
    main()

Output

255

The OR of bitwise operations is |
The AND of bitwise operations is &

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << (1 | 2 | 4 | 8 | 16 | 32 | 64 | 128) << endl;
    cin.get();
    return 0;
}

Output

255

The OR of bitwise operations is |
The AND of bitwise operations is &


Four arithmetic operations and increment operators

Python

def main():
    print(20%7)
    print(3**2)
    a=10
    a+=1
    a+=2
    print(a)
if __name__=='__main__':
    main()

Output

6
9
13

The operator to calculate the remainder of a division is %.
Compute powers (powers of magnitude) with the ** operator
There is no operator named ++.

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << (20 % 7) << endl;
    cout << pow(3, 2) << endl;
    int a = 10;
    a++;
    a += 2;
    cout << a << endl;
    cin.get();
    return 0;
}

Output

6
9
13

The operator to calculate the remainder of a division is %.
Calculating powers of a power with the pow function
The increment operator ++ is an operator that adds 1


Integer division

Python

def main():
    print(5//2)
    print(5/2)
if __name__=='__main__':
    main()

Output

2
2.5

Integer division is //.
Floating point numbers can be divided by /.

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << (5 / 2) << endl;
    cout << (5.0 / 2.0) << endl;
    cin.get();
    return 0;
}

Output

2
2.5

Since both 5 and 2 are integers, 5/2 is division between integers
Since both 5.0 and 2.0 are floating-point numbers, 5.0/2.0 is division between floating-point numbers


exponential notation

Python

def main():
    print(1e2)
    print(1e-2)
if __name__=='__main__':
    main()

Output

100.0
0.01

1e2 represents 1 x 102
1e-2 represents 1 × 10-2

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << 1e2 << endl;
    cout << 1e-2 << endl;
    cin.get();
    return 0;
}

Output

100
0.01

1e2 represents 1 x 102
1e-2 represents 1 × 10-2


NaN

Python

import numpy as np
def main():
    a=1
    b=-1
    a=np.sqrt(a)
    b=np.sqrt(b)
    print(a)
    print(b)
    print(np.isnan(a))
    print(np.isnan(b))
if __name__=='__main__':
    main()

Output

c:/!temp/pytest/myprogram.py:6: RuntimeWarning: invalid value encountered in sqrt
  b=np.sqrt(b)
1.0
nan
False
True

NaN (Not a Number) is checked with the isnan function
If you have a bug caused by NaN, it helps to find the location of the NaN
The isnan function is not a fundamental solution.
    In this case, the program and data should be such that sqrt does not contain negative values.
    If the specification allows for negative values in sqrt, check the argument of sqrt before calling sqrt with an if statement, etc.
    Create a program that checks the arguments before computing sqrt, instead of checking if the result is NaN after computing sqrt.

C++

#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char** argv)
{
    double a = 1.0;
    double b = -1.0;
    a = sqrt(a);
    b = sqrt(b);
    cout << a << endl;
    cout << b << endl;
    if (isnan(a)) cout << "true" << endl;
    else cout << "false" << endl;
    if (isnan(b)) cout << "true" << endl;
    else cout << "false" << endl;
    cin.get();
    return 0;
}

Output

1
-nan(ind)
false
true

NaN (Not a Number) is checked with the isnan function
If you have a bug caused by NaN, it helps to find the location of the NaN
The isnan function is not a fundamental solution.
    In this case, the program and data should be such that sqrt does not contain negative values.
    If the specification allows for negative values in sqrt, check the argument of sqrt before calling sqrt with an if statement, etc.
    Create a program that checks the arguments before computing sqrt, instead of checking if the result is NaN after computing sqrt.


Tuple

Python

def main():
    a0=1
    a1='abc'
    a=(a0,a1)
    print(a[0])
    print(a[1])
    b0,b1=a
    print(b0)
    print(b1)
if __name__=='__main__':
    main()

Output

1
abc
1
abc

Tuples (pairs) are denoted by commas
    Enclosing in round brackets is normal.
Python makes extensive use of tuples.
Tuples can also be broken down into their respective elements

C++

#include <iostream>
#include <tuple>
using namespace std;
int main(int argc, char** argv)
{
    int a0 = 1;
    string a1 = "abc";
    auto a = make_tuple(a0, a1);
    cout << get<0>(a) << endl;
    cout << get<1>(a) << endl;
    auto [b0, b1] = a;
    cout << b0 << endl;
    cout << b1 << endl;
    cin.get();
    return 0;
}

Output

1
abc
1
abc

Some libraries can use tuples (pairs).
If that library is designed to use tuples, you should use tuples.
    If you only use libraries that rarely use tuples, you should not use tuples
Some libraries provide pairs as a two-pair tuple.
Tuples can also be broken down into their respective elements


Array

Python

def main():
    a=[0,0]
    a[0]=10
    a[1]=20
    b=[2,3]
    b[0]=b[1]+1
    c=[[1,2],[3,4]]
    d=[0]*2
    d[0]=100
    d[1]=200
    print(a)
    print(b)
    print(c)
    print(d)
if __name__=='__main__':
    main()

Output

[10, 20]
[4, 3]
[[1, 2], [3, 4]]
[100, 200]

List

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a[2];
    a[0] = 10;
    a[1] = 20;
    int b[2] = { 2,3 };
    b[0] = b[1] + 1;
    int c[2][2] = { {1,2},{3,4} };
    int* d;
    d = new int[2];
    d[0] = 100;
    d[1] = 200;
    cout << a[0] << " " << a[1] << endl;
    cout << b[0] << " " << b[1] << endl;
    cout << c[0][0] << " " << c[0][1] << " " << c[1][0] << " " << c[1][1] << endl;
    cout << d[0] << " " << d[1] << endl;
    cin.get();
    return 0;
}

Output

10 20
4 3
1 2 3 4
100 200

Array
Types marked with * are called pointer types
Array types are also pointer types
Memory can be allocated with the new operator.


type conversion

Python

def main():
    a=5
    b=2
    print(float(a)/float(b))
    c=[1,2]
    d=1.01
    print(c[int(d)])
if __name__=='__main__':
    main()

Output

2.5
2

Data types can be converted by writing float, int, etc.
Consider the intent of the program carefully and convert data types appropriately for implementation.

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a = 5;
    int b = 2;
    cout << (double)a / (double)b << endl;
    int c[2] = { 1,2 };
    double d = 1.01;
    cout << c[(int)d] << endl;
    cin.get();
    return 0;
}

Output

2.5
2

Data types can be converted by writing double, int, etc.
Consider the intent of the program carefully and convert data types appropriately for implementation.


string concatenation

Python

def main():
    a='a'
    b='b'
    c=0
    print(a+b)
    print(a+str(c)+'c')
if __name__=='__main__':
    main()

Output

ab
a0c

Strings can be concatenated with the + operator.
Numeric values are converted to strings by type conversion to type str

C++

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
    string a = "a";
    string b = "b";
    int c = 0;
    cout << (a + b) << endl;
    cout << (a + to_string(c) + "c") << endl;
    cin.get();
    return 0;
}

Output

ab
a0c

Strings can be concatenated with the + operator.
Numeric values are converted to strings with the to_string function.


formatted character string

Python

def main():
    y=1234
    m=5
    d=6
    a=f'{y:4d}/{m:2d}/{d:2d}'
    b='{0:04d}/{1:02d}/{2:02d}'.format(y,m,d)
    c='{0:d}/{1:d}/{2:d}'.format(y,m,d)
    print(a)
    print(b)
    print(c)
if __name__=='__main__':
    main()

Output

1234/ 5/ 6
1234/05/06
1234/5/6

String can be formatted with the format function.
Can format strings with f-string

C++

#include <iostream>
#include <format>
using namespace std;
int main(int argc, char** argv)
{
    int y = 1234;
    int m = 5;
    int d = 6;
    int n = snprintf(nullptr, 0, "%4d/%2d/%2d", y, m, d);
    char* s = new char[n + 1];
    snprintf(s, n + 1, "%4d/%2d/%2d", y, m, d);
    string a = s;
    string b = format("{0:04d}/{1:02d}/{2:02d}", y, m, d);
    string c = format("{0:d}/{1:d}/{2:d}", y, m, d);
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cin.get();
    return 0;
}

Output

1234/ 5/ 6
1234/05/06
1234/5/6

String can be formatted with the format function.
Note that the format function is a function of the latest C++ and cannot be used by some compilers.
If the format function is not available, use the snprintf function instead


standard input

Python

def main():
    print('文字を入力してください')
    s=input()
    print("入力した文字は'"+s+"'です")
    print('整数を入力してください')
    i=int(input())
    print("入力した整数は'"+str(i)+"'です")
    print('実数を入力してください')
    f=float(input())
    print("入力した実数は'"+str(f)+"'です")
    print('Enterキーを押してください')
    input()
if __name__=='__main__':
    main()

Output

文字を入力してください
abc
入力した文字は'abc'です
整数を入力してください
10
入力した整数は'10'です
実数を入力してください
1.5
入力した実数は'1.5'です
Enterキーを押してください

Use the input function to input text from the console

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    string s;
    cout << "文字を入力してください" << endl;
    cin >> s;
    cout << "入力した文字は'" << s << "'です" << endl;
    int i;
    cout << "整数を入力してください" << endl;
    cin >> i;
    cout << "入力した整数は'" << i << "'です" << endl;
    double d;
    cout << "実数を入力してください" << endl;
    cin >> d;
    cout << "入力した実数は'" << d << "'です" << endl;
    cin.ignore();
    cout << "Enterキーを押してください" << endl;
    cin.get();
    return 0;
}

Output

文字を入力してください
abc
入力した文字は'abc'です
整数を入力してください
10
入力した整数は'10'です
実数を入力してください
1.5
入力した実数は'1.5'です
Enterキーを押してください

Character input from console is streamed from cin to variable with stream operator >>


while statement

Python

def main():
    a=0
    while True:
        print(a)
        a+=1
        if a>=10:
            break
if __name__=='__main__':
    main()

Output

0
1
2
3
4
5
6
7
8
9

The range of the while statement is indicated by indentation.
The same applies to for and if statements, etc.

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a = 0;
    while (true) {
        cout << a << endl;
        a++;
        if (a >= 10)break;
    }
    cin.get();
    return 0;
}

Output

0
1
2
3
4
5
6
7
8
9

The range of the while statement is the range enclosed by { and }.
If there is only one line of the imperative sentence, it does not need to be enclosed in { and }.
The same applies to for and if statements, etc.


if statement

Python

def main():
    a,b,c=1,2,3
    if a==0:
        print('a==0')
    elif a==1:
        print('a==1')
    else:
        print('a==?')
    if a==1 and b!=1:
        print('a==1 and b!=1')
    if not a==2 or b==2:
        print('not a==2 or b==2')
    if not (a==2 or b==2):
        print('not (a==2 or b==2)')
    if a<b and b<c:
        print('a<b and b<c')
    if c>b>a:
        print('c>b>a')
if __name__=='__main__':
    main()

Output

a==1
a==1 and b!=1
not a==2 or b==2
a<b and b<c
c>b>a

elif stands for else if.
Use and, or, not, ==, !=, <, >, <=, >=, etc. as logical operators
Multiple operators can be connected together like c>b>a

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a = 1, b = 2, c = 3;
    if (a == 0)cout << "a==0" << endl;
    else if (a == 1)cout << "a==1" << endl;
    else cout << "a==?" << endl;
    if (a == 1 && b != 1)cout << "a==1&&b!=1" << endl;
    if (!(a == 2) || b == 2)cout << "!(a==2)||b==2" << endl;
    if (!(a == 2 || b == 2))cout << "!(a==2||b==2)" << endl;
    if (a < b && b < c)cout << "a<b&&b<c" << endl;
    if (c > b > a)cout << "c>b>a" << endl;
    cin.get();
    return 0;
}

Output

a==1
a==1&&b!=1
!(a==2)||b==2
a<b&&b<c

The equivalent of elif is else if
Use &&, ||, !, ==, !=, <, >, <=, >=, etc. as logical operators
You cannot use multiple operators connected together like c>b>a
    In this case c>b&&b>a


conditional operator

Python

def main():
    a=7
    b='even' if a%2==0 else 'odd'
    print(b)
if __name__=='__main__':
    main()

Output

odd

if statement in the middle of an imperative statement
(if true) if (condition) else (if false)

C++

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a = 7;
    string b = (a % 2 == 0) ? "even" : "odd";
    cout << b << endl;
    cin.get();
    return 0;
}

Output

odd

conditional operator
(Condition) ? (if true) : (if false)


Lists, sorts and medians

Python

def main():
    a=[]
    a.append(30)
    a.append(40)
    a.append(20)
    a.append(10)
    a.append(50)
    print(a)
    a.sort()
    print(a)
    print('メディアンは',a[len(a)//2])
if __name__=='__main__':
    main()

Output

[30, 40, 20, 10, 50]
[10, 20, 30, 40, 50]
メディアンは 30

Add to list with append
Sorting with the sort function
Get length with len function

C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
    vector<int> a;
    a.push_back(30);
    a.push_back(40);
    a.push_back(20);
    a.push_back(10);
    a.push_back(50);
    cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << " " << a[4] << endl;
    sort(a.begin(), a.end());
    cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << " " << a[4] << endl;
    cout << "メディアンは" << a[a.size() / 2] << endl;
    cin.get();
    return 0;
}

Output

30 40 20 10 50
10 20 30 40 50
メディアンは30

vector is a list (vector is usually called a dynamic array, not a list)
    Specify the data type of the element as <int>
Add to list with push_back
Sorting with the sort function
Get the length with the size function


Median

Python

import numpy as np
def main():
    a=[30,40,20,10,50]
    print(a)
    print('メディアンは',np.median(a))
    print(a)
if __name__=='__main__':
    main()

Output

[30, 40, 20, 10, 50]
メディアンは 30.0
[30, 40, 20, 10, 50]

median is faster if you just want to calculate median
    Sort is O(NlogN) but selection is O(N)
The original list is not sorted.

C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
    vector<int> a = { 30,40,20,10,50 };
    for (int x : a)cout << x << " ";
    cout << endl;
    nth_element(a.begin(), a.begin() + a.size() / 2, a.end());
    cout << "メディアンは" << a[a.size() / 2] << endl;
    for (int x : a)cout << x << " ";
    cout << endl;
    cin.get();
    return 0;
}

Output

30 40 20 10 50
メディアンは30
10 20 30 40 50

nth_element is faster if you just want to calculate median
    Sort is O(NlogN) but selection is O(N)
The original list sorts correctly only for medians, but not necessarily for other numbers
    nth_element is used to calculate the median, not for sorting


for statement

Python

def main():
    data=[10,20,30,40,50]
    sum=0
    for val in data:
        sum+=val
    print(sum)
    sum=0
    for i in range(0,5):
        sum+=data[i]
    print(sum)
if __name__=='__main__':
    main()

Output

150
150

All for statements in Python are range-based for statements (foreach statements)

C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
    vector<int> data = { 10,20,30,40,50 };
    int sum = 0;
    for (int val : data)sum += val;
    cout << sum << endl;
    sum = 0;
    for (int i = 0; i < 5; i++)sum += data[i];
    cout << sum << endl;
    cin.get();
    return 0;
}

Output

150
150

A range-based for statement (foreach statement) is written like a for (element : collection)
You can also use for statements such as for(expression1 ; expression2 ; expression3)
    Expression 1 is executed before entering the loop
    Expression 2 is evaluated at the beginning of the loop, and if true, the loop is executed; if false, the loop is exited
    Equation 3 is executed at the end of the loop


enumerate

Python

def main():
    data=[10,30,50,40,20]
    maxval=0
    maxinx=0
    for i, val in enumerate(data):
        if val>maxval:
            maxval=val
            maxinx=i
    print(data)
    print(maxval)
    print(maxinx)
if __name__=='__main__':
    main()

Output

[10, 30, 50, 40, 20]
50
2

enumerate exists

C++

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
    vector<int> data = { 10,30,50,40,20 };
    int maxval = 0;
    int maxinx = 0;
    for (int i = 0; i < data.size(); i++) {
        int val = data[i];
        if (val > maxval) {
            maxval = val;
            maxinx = i;
        }
        cout << data[i] << " ";
    }
    cout << endl;
    cout << maxval << endl;
    cout << maxinx << endl;
    cout << endl;
    maxval = 0;
    maxinx = 0;
    int i;
    vector<int>::iterator val;
    for (i = 0, val = data.begin(); val != data.end(); i++, val++) {
        if (*val > maxval) {
            maxval = *val;
            maxinx = i;
        }
        cout << *val << " ";
    }
    cout << endl;
    cout << maxval << endl;
    cout << maxinx << endl;
    cin.get();
    return 0;
}

Output

10 30 50 40 20
50
2

10 30 50 40 20
50
2

enumerate does not exist


list inclusion notation

Python

def main():
    a=[2,4,8]
    a=[256/b for b in a]
    print(a)
if __name__=='__main__':
    main()

Output

[128.0, 64.0, 32.0]

You can use list inclusion notation

C++

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
    int a[] = { 2,4,8 };
    for (int i = 0; i < 3; i++) {
        a[i] = 256 / a[i];
    }
    for (int i = 0; i < 3; i++)cout << a[i] << " ";
    cout << endl;
    vector<int> aa = { 2,4,8 };
    for (int& bb : aa) {
        bb = 256 / bb;
    }
    for (int cc : aa)cout << cc << " ";
    cout << endl;
    cin.get();
    return 0;
}

Output

128 64 32
128 64 32

You cannot use list inclusion notation


Function

Python

def myfunc(a,b,c):
    a+=1
    b+=1
    c[0]+=1
    c[1]+=1
    return str(a)+'+'+str(b)+'='+str(a+b)
def main():
    x=1
    y=2
    z=[3,4]
    w=myfunc(x,y,z)
    print(x)
    print(y)
    print(z)
    print(w)
if __name__=='__main__':
    main()

Output

1
2
[4, 5]
2+3=5

Function behavior is the same as general programming languages
Carefully consider whether the value of a variable in a function affects the outside of the function or not, and implement it accordingly.

C++

#include <iostream>
#include <string>
using namespace std;
string myfunc(int a, int b, int* c) {
    a++;
    b++;
    c[0]++;
    c[1]++;
    return to_string(a) + "+" + to_string(b) + "=" + to_string(a + b);
}
int main(int argc, char** argv)
{
    int x = 1;
    int y = 2;
    int z[2] = { 3,4 };
    string w = myfunc(x, y, z);
    cout << x << endl;
    cout << y << endl;
    cout << z[0] << " " << z[1] << endl;
    cout << w << endl;
    cin.get();
    return 0;
}

Output

1
2
4 5
2+3=5

Function behavior is the same as general programming languages
Carefully consider whether the value of a variable in a function affects the outside of the function or not, and implement it accordingly.


Call by reference

Python

def myfunc(a,b,c,d):
    a=10
    b[0]=20
    c=[30,40]
    d[0]=[50,60]
    e=[70,80]
    return e
def main():
    a=1
    b=[2]
    c=[3,4]
    d=[[5,6]]
    e=[7,8]
    e=myfunc(a,b,c,d)
    print(a)
    print(b)
    print(c)
    print(d)
    print(e)
if __name__=='__main__':
    main()

Output

1
[20]
[3, 4]
[[50, 60]]
[70, 80]

Note that all Python function arguments are said to be call by reference, but there is a function equivalent to call by value

C++

#include <iostream>
using namespace std;
int* myfunc(int a, int& b, int* c, int*& d) {
    a = 10;
    b = 20;
    int* cc = new int[2]{ 30,40 };
    c = cc;
    int* dd = new int[2]{ 50,60 };
    d = dd;
    int* ee = new int[2]{ 70,80 };
    return ee;
}
int main(int argc, char** argv)
{
    int a = 1;
    int b = 2;
    int c[2] = { 3,4 };
    int* d = new int[2]{ 5,6 };
    int* e = new int[2]{ 7,8 };
    e = myfunc(a, b, c, d);
    cout << a << endl;
    cout << b << endl;
    cout << c[0] << " " << c[1] << endl;
    cout << d[0] << " " << d[1] << endl;
    cout << e[0] << " " << e[1] << endl;
    cin.get();
    return 0;
}

Output

1
20
3 4
50 60
70 80

Use & for call by reference in function arguments
a is call by value of type int, b is call by reference of type int
    The contents of a have no effect outside of the function.
    The contents of b affect even outside the function.
c is call by value of type int*, d is call by reference of type int*.
    The contents of c have no effect outside of the function.
    The contents of d affect even outside the function.


Local and global variables

Python

a=1
def myfunc1(a):
    a=2
def myfunc2():
    a=3
def myfunc3():
    global a
    a=4
def main():
    global a
    print(a)
    a=5
    print(a)
    myfunc1(a)
    print(a)
    myfunc2()
    print(a)
    myfunc3()
    print(a)
    while True:
        a=6
        break
    print(a)
    while True:
        a=7
        break
    print(a)
if __name__=='__main__':
    main()

Output

1
5
5
5
4
6
7

Variables designated “global” can be used as global variables

C++

#include <iostream>
using namespace std;
int a = 1;
void myfunc1(int a) {
    a = 2;
}
void myfunc2() {
    int a = 3;
}
void myfunc3() {
    a = 4;
}
int main(int argc, char** argv)
{
    cout << a << endl;
    a = 5;
    cout << a << endl;
    myfunc1(a);
    cout << a << endl;
    myfunc2();
    cout << a << endl;
    myfunc3();
    cout << a << endl;
    while (true) {
        int a = 6;
        break;
    }
    cout << a << endl;
    while (true) {
        a = 7;
        break;
    }
    cout << a << endl;
    cin.get();
    return 0;
}

Output

1
5
5
5
4
4
7

Variables not defined within a function use global variables.


Class

Python

import numpy as np
class player:
    def __init__(self,l):
        self.life=l
    def damage(self,d):
        self.life-=d
def main():
    hero=player(100)
    for _ in range(0,5):
        d=np.random.randint(0,20)
        print('life='+str(hero.life)
        +' damage='+str(d),end='')
        hero.damage(d)
        print(' life='+str(hero.life))
if __name__ == '__main__':
    main()

Output

life=100 damage=16 life=84
life=84 damage=11 life=73
life=73 damage=3 life=70
life=70 damage=15 life=55
life=55 damage=0 life=55

There is no need to explain object-oriented programming for a program of only a few thousand lines, so I will omit the explanation.

C++

#include <iostream>
#include <string>
#include <random>
using namespace std;
class player {
public:
    int life = 0;
    player(int l) {
        life = l;
    }
    void damage(int d) {
        life -= d;
    }
};
int main(int argc, char** argv)
{
    random_device srand;
    mt19937 next(srand());
    uniform_int_distribution<> rand(0, 19);
    player hero(100);
    for (int i = 0; i < 5; i++) {
        int d = rand(next);
        cout << "life=" + to_string(hero.life)
            + " damage=" + to_string(d);
        hero.damage(d);
        cout << " life=" + to_string(hero.life) << endl;
    }
    cin.get();
    return 0;
}

Output

life=100 damage=10 life=90
life=90 damage=3 life=87
life=87 damage=12 life=75
life=75 damage=13 life=62
life=62 damage=4 life=58

There is no need to explain object-oriented programming for a program of only a few thousand lines, so I will omit the explanation.


Class

Python

class card:
    def __init__(self,n):
        self.name=n
    def __repr__(self):
        return self.name

class item(card):
    def __init__(self,n,e):
        super().__init__(n)
        self.energy=e
    def __repr__(self):
        return self.name+'('+str(self.energy)+')'

class idol(card):
    def __init__(self,n,s):
        super().__init__(n)
        self.stamina=s
    def __repr__(self):
        return self.name+'('+str(self.stamina)+')'
    def charge(self,i):
        self.stamina+=i.energy

def main():
    cards=[idol('Anzu Futaba',100),item('Candy',10)]
    print(cards)
    cards[0].charge(cards[1])
    cards.remove(cards[1])
    print(cards)

if __name__ == '__main__':
    main()

Output

[Anzu Futaba(100), Candy(10)]
[Anzu Futaba(110)]

There is no need to explain object-oriented programming for a program of only a few thousand lines, so I will omit the explanation.

C++

#include <iostream>
#include <string>
using namespace std;
class card {
public:
    string name;
    int stamina = 0;
    int energy = 0;
    card(string n) {
        name = n;
    }
    virtual string tostring() {
        return name;
    }
    virtual void charge(card* i) {
    }
};
class item :public card {
public:
    item(string n, int e) : card(n) {
        this->energy = e;
    }
    string tostring() override {
        return this->name + "(" + to_string(this->energy) + ")";
    }
};
class idol : public card {
public:
    idol(string n, int s) : card(n) {
        this->stamina = s;
    }
    string tostring() override {
        return this->name + "(" + to_string(this->stamina) + ")";
    }
    void charge(card* i) override {
        this->stamina += i->energy;
    }
};
int main(int argc, char** argv)
{
    vector<card*> cards = { new idol("Anzu Futaba", 100), new item("Candy", 10) };
    for (card* c : cards)cout << c->tostring() << " ";
    cout << endl;
    cards[0]->charge(cards[1]);
    cards.erase(cards.begin() + 1);
    for (card* c : cards)cout << c->tostring() << " ";
    cout << endl;
    cin.get();
    return 0;
}

Output

Anzu Futaba(100) Candy(10)
Anzu Futaba(110)

There is no need to explain object-oriented programming for a program of only a few thousand lines, so I will omit the explanation.


Lambda expressions and overloading of operators

Python

def addfunc(a):
    return lambda b: a+b
class addclass:
    def __init__(self,d):
        self.e=d
    def __call__(self,f):
        return self.e+f
def main():
    print(addfunc(1)(2))
    print(addclass(1)(2))
if __name__=='__main__':
    main()

Output

3
3

When you give two arguments to a function, you call it like func(value1,value2), so you may often think that func(value1)(value2) is a bug.
Today's programming languages are so rich in features that you can write all kinds of programs, so don't be bound by conventional wisdom.
Let's understand the usage of that library and function definitions well and implement them!
This class does not explain this source code because it can be implemented without lambda expressions or proprietary classes

C++

#include <iostream>
using namespace std;
auto addfunc(int a) {
    return [a](int b) { return a + b; };
}
class addclass {
    int result = 0;
public:
    addclass operator()(int val) {
        this->result += val;
        return *this;
    }
    operator int() {
        return result;
    }
};
int main() {
    cout << addfunc(1)(2) << endl;
    addclass add;
    cout << add(1)(2) << endl;
    return 0;
}

Output

3
3

When you give two arguments to a function, you call it like func(value1,value2), so you may often think that func(value1)(value2) is a bug.
Today's programming languages are so rich in features that you can write all kinds of programs, so don't be bound by conventional wisdom.
Let's understand the usage of that library and function definitions well and implement them!
This class does not explain this source code because it can be implemented without lambda expressions or proprietary classes


Generator and iterator

Python

def week():
    week=['mon','tue','wed','thu','fri','sat','sun']
    while True:
        for s in week:
            yield s
def main():
    generator=week()
    for _ in range(0,30):
        print(next(generator))
if __name__=='__main__':
    main()

Output

mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue

This class can be implemented without using a generator, so no explanation is given.

C++

#include <iostream>
#include <coroutine>
#include <vector>
using namespace std;

template <typename T>
struct generator {
    struct promise_type {
        T value_;
        auto get_return_object()
        {
            return generator{ *this };
        };
        auto initial_suspend()
        {
            return suspend_always{};
        }
        auto final_suspend() noexcept
        {
            return suspend_always{};
        }
        auto yield_value(T v)
        {
            value_ = v;
            return suspend_always{};
        }
        void return_void() {}
        void unhandled_exception() { terminate(); }
    };
    using coro_handle = coroutine_handle<promise_type>;
    struct iterator {
        coro_handle coro_;
        bool done_;
        iterator& operator++()
        {
            coro_.resume();
            done_ = coro_.done();
            return *this;
        }
        bool operator!=(const iterator& rhs) const
        {
            return done_ != rhs.done_;
        }
        T operator*() const
        {
            return coro_.promise().value_;
        }
    };
    ~generator()
    {
        if (coro_)
            coro_.destroy();
    }
    generator(generator const&) = delete;
    generator(generator&& rhs) noexcept
        : coro_(exchange(rhs.coro_, nullptr)) {}
    iterator begin()
    {
        coro_.resume();
        return { coro_, coro_.done() };
    }
    iterator end()
    {
        return { {}, true };
    }
private:
    explicit generator(promise_type& p)
        : coro_(coro_handle::from_promise(p)) {}
    coro_handle coro_;
};

generator<string> week()
{
    vector<string> week = { "mon","tue","wed","thu","fri","sat","sun" };
    while (true) {
        for (string s : week) {
            co_yield s;
        }
    }
}

int main()
{
    generator<string> g = week();
    int i = 0;
    for (auto s:g) {
        cout << s << endl;
        i++;
        if (i == 30)break;
    }
}

Output

mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue
wed
thu
fri
sat
sun
mon
tue

This class can be implemented without using a generator, so no explanation is given.
This program in C++ doesn't need much help.


Assert

Python

def func(a,b):
    assert abs(b)>1e-15, 'argument 2 is zero'
    return a/b
def main():
    a=0
    b=1
    print(func(a,b))
    print(func(b,a))
if __name__=='__main__':
    main()

Output

0.0
Traceback (most recent call last):
  File "c:/!temp/pytest/myprogram.py", line 10, in <module>
    main()
  File "c:/!temp/pytest/myprogram.py", line 8, in main
    print(func(b,a))
  File "c:/!temp/pytest/myprogram.py", line 2, in func
    assert abs(b)>1e-15, 'argument 2 is zero'
AssertionError: argument 2 is zero

Since students are not likely to set up their own assertions, it is OK if they do not know anything about assertions!

C++

#include <iostream>
#include <cassert>
using namespace std;
double func(double a, double b)
{
    assert(abs(b) > 1e-15);
    return a / b;
}
int main(int argc, char** argv)
{
    double a = 0.0;
    double b = 1.0;
    cout << func(a, b) << endl;
    cout << func(b, a) << endl;
    cin.get();
    return 0;
}

Output

0
Assertion failed: abs(b) > 1e-15, file C:\!temp\PhotometricStereo\PhotometricStereo\PhotometricStereo.cpp, line 6

Since students are not likely to set up their own assertions, it is OK if they do not know anything about assertions!


Generating Matrices

Python

import numpy as np
def main():
    a=np.zeros((3,2),dtype=np.float64)
    a[1,0]=1
    print(a)
    rows,cols=a.shape
    print('rows are',rows,'and columns are',cols)
if __name__=='__main__':
    main()

Output

[[0. 0.]
 [1. 0.]
 [0. 0.]]
rows are 3 and columns are 2

Can create a matrix initialized with zeros in numpy
argument specifies the rows and columns of the matrix
dtype specifies the data type of an element
For example, np.float64 for a 64-bit floating-point number and np.uint8 for an 8-bit unsigned integer
shape can be used to get the number of rows and columns in a matrix
Access elements by [row number, column number

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = Mat::zeros(3, 2, CV_64F);
    a.at<double>(1, 0) = 1.0;
    cout << a << endl;
    cout << "rows are " << a.rows << " and columns are " << a.cols << endl;
    cin.get();
    return 0;
}

Output

[0, 0;
 1, 0;
 0, 0]
rows are 3 and columns are 2

Mat::zeros in OpenCV can be used to create matrices initialized with zeros
argument specifies the rows and columns of the matrix
Argument specifies the data type of the element
For example, CV_64F for a 64-bit floating-point number and CV_8U for an 8-bit unsigned integer
rows and cols can be used to get the number of rows and columns in a matrix
Access elements by at<element data type>(row number,column number)


Matrix Initialization and Multiplication

Python

import numpy as np
def main():
    a=np.array([[1,2],[2,4]],dtype=np.float64)
    b=np.array([[3],[1]],dtype=np.float64)
    c=a@b
    print(a)
    print(b)
    print(c)
if __name__=='__main__':
    main()

Output

[[1. 2.]
 [2. 4.]]
[[3.]
 [1.]]
[[ 5.]
 [10.]]

np.array can convert a list into a numpy matrix
Use @ to multiply matrices together.

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = (Mat_<double>(2, 2) << 1, 2, 2, 4);
    Mat b = (Mat_<double>(2, 1) << 3, 1);
    Mat c = a * b;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cin.get();
    return 0;
}

Output

[1, 2;
 2, 4]
[3;
 1]
[5;
 10]

Mat_<data type>(row,column) can be populated with values using the stream operator<< to create a matrix of those numbers
Use * to multiply matrices together.


Slice (submatrix)

Python

import numpy as np
def main():
    a=np.array([[0,1,2,3,4],[5,6,7,8,9]],
    dtype=np.float64)
    b=a[:,1:4]
    print(a)
    print(b)
if __name__=='__main__':
    main()

Output

[[0. 1. 2. 3. 4.]
 [5. 6. 7. 8. 9.]]
[[1. 2. 3.]
 [6. 7. 8.]]

Slice (submatrix)
where: denotes all rows
1:4 indicates row 1 or more but less than row 4
    However, the leftmost column is the 0th row.

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = (Mat_<double>(2, 5) <<
        0, 1, 2, 3, 4,
        5, 6, 7, 8, 9);
    Mat b = a(Range::all(), Range(1, 4));
    cout << a << endl;
    cout << b << endl;
    cin.get();
    return 0;
}

Output

[0, 1, 2, 3, 4;
 5, 6, 7, 8, 9]
[1, 2, 3;
 6, 7, 8]

Slice (submatrix)
Range::all() represents all rows
Range(1,4) represents columns 1 through 4
    However, the leftmost column is the 0th row.


inverse matrix

Python

import numpy as np
def main():
    a=np.array([[2,0],[0,2]],dtype=np.float64)
    b=np.linalg.inv(a)
    c=a@b
    print(a)
    print(b)
    print(c)
if __name__=='__main__':
    main()

Output

[[2. 0.]
 [0. 2.]]
[[0.5 0. ]
 [0. 0.5]]
[[1. 0.]
 [0. 1.]]

You can compute the inverse with numpy's linalg inv

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = (Mat_<double>(2, 2) << 2, 0, 0, 2);
    Mat b = a.inv();
    Mat c = a * b;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cin.get();
    return 0;
}

Output

[2, 0;
 0, 2]
[0.5, 0;
 0, 0.5]
[1, 0;
 0, 1]

Inverse matrix can be computed with OpenCV Mat inv.


simultaneous linear equations

Python

import numpy as np
def main():
    a=np.array([[1,2],[2,3]],dtype=np.float64)
    b=np.array([[2],[2]],dtype=np.float64)
    x=np.linalg.solve(a,b)
    print(a)
    print(b)
    print(x)
    print('連立線形方程式')
    print(a[0,0],'x +',a[0,1],'y =',b[0,0])
    print(a[1,0],'x +',a[1,1],'y =',b[1,0])
    print('の解は')
    print('x =',x[0,0])
    print('y =',x[1,0])
if __name__=='__main__':
    main()

Output

[[1. 2.]
[2. 3.]]
[[2.]
[2.]]
[[-2.]
[ 2.]]
連立線形方程式
1.0 x + 2.0 y = 2.0
2.0 x + 3.0 y = 2.0
の解は
x = -2.0
y = 2.0

Solve the simultaneous linear equation Ax=b by the solve function
Problem where A and b are inputs and I want to find x
A is a matrix and x and b are vectors
Function to multiply the inverse of A by b

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = (Mat_<double>(2, 2) << 1, 2, 2, 3);
    Mat b = (Mat_<double>(2, 1) << 2, 2);
    Mat x;
    solve(a, b, x);
    cout << a << endl;
    cout << b << endl;
    cout << x << endl;
    cout << "連立線形方程式" << endl;
    cout << a.at<double>(0, 0) << "x+" << a.at<double>(0, 1) << "y=" << b.at<double>(0, 0) << endl;
    cout << a.at<double>(1, 0) << "x+" << a.at<double>(1, 1) << "y=" << b.at<double>(1, 0) << endl;
    cout << "の解は" << endl;
    cout << "x=" << x.at<double>(0, 0) << ", y=" << x.at<double>(1, 0) << endl;
    cin.get();
    return 0;
}

Output

[1, 2;
2, 3]
[2;
2]
[-2;
2]
連立線形方程式
1x+2y=2
2x+3y=2
の解は
x=-2, y=2

Solve the simultaneous linear equation Ax=b by the solve function
Problem where A and b are inputs and I want to find x
A is a matrix and x and b are vectors
Function to multiply the inverse of A by b


Deep matrix copy

Python

import numpy as np
def main():
    a=np.ones((2,1),dtype=np.float64)
    b=a
    c=a.copy()
    a[0,0]=2
    b[0,0]=3
    c[0,0]=4
    print(a)
    print(b)
    print(c)
if __name__=='__main__':
    main()

Output

[[3.]
 [1.]]
[[3.]
 [1.]]
[[4.]
 [1.]]

If you write it like b=a, the reference is substituted.
    Changing b changes a in the same way, and changing a changes b in the same way
    Both a and b refer to the same entity.
If we make a duplicate like c=a.copy() and then substitute, a and c will be two separate matrices

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat a = Mat::ones(2, 1, CV_64F);
    Mat b = a;
    Mat c = a.clone();
    a.at<double>(0, 0) = 2;
    b.at<double>(0, 0) = 3;
    c.at<double>(0, 0) = 4;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cin.get();
    return 0;
}

Output

[3;
 1]
[3;
 1]
[4;
 1]

If you write it like b=a, the reference is substituted.
    Changing b changes a in the same way, and changing a changes b in the same way
    Both a and b refer to the same entity.
If we make a duplicate like c=a.clone() and then substitute, a and c will be two separate matrices


Singular Value Decomposition

Python

import numpy as np
def main():
    a=np.array([[1,0],[0,2]],dtype=np.float64)
    u,w,vt=np.linalg.svd(a,full_matrices=False)
    print('特異値分解の結果')
    print('A =',a)
    print('U =',u)
    print('W =',w)
    print('V^T =',vt)
    w=np.diag(w)
    check=u@w@vt
    print('U W V^T =',check)
if __name__=='__main__':
    main()

Output

特異値分解の結果
A = [[1. 0.]
 [0. 2.]]
U = [[0. 1.]
 [1. 0.]]
W = [2. 1.]
V^T = [[0. 1.]
 [1. 0.]]
U W V^T = [[1. 0.]
 [0. 2.]]

Specifying false for full_matrices as an argument to the singular value decomposition SVD
    There is no point in calling it True.
Specify the matrix you want to decompose as an argument to numpy's linalg svd
The calculation results are returned in the order U,W,V^T
It returns in V^T, not V.
W is returned in vector form with diagonal components only, not in matrix form
Can be converted to a diagonal matrix with the diag function

C++

#include <iostream>
#include <intrin.h>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    _mm_setcsr(_mm_getcsr() | 0x8040);
    Mat a = (Mat_<double>(2, 2) << 1, 0, 0, 2);
    SVD svd(a);
    cout << "特異値分解の結果" << endl;
    cout << "A=" << a << endl;
    cout << "U=" << svd.u << endl;
    cout << "W=" << svd.w << endl;
    cout << "V^T=" << svd.vt << endl;
    Mat w = Mat::diag(svd.w);
    Mat check = svd.u * w * svd.vt;
    cout << "U W V^T = " << check << endl;
    cin.get();
    return 0;
}

Output

特異値分解の結果
A=[1, 0;
 0, 2]
U=[0, 1;
 1, 0]
W=[2;
 1]
V^T=[0, 1;
 1, 0]
U W V^T = [1, 0;
 0, 2]

_mm_setcsr(_mm_getcsr()|0x8040); is called as "spell"
    Calling this will speed things up, but you can turn it off if you're not sure.
Specify the matrix to be decomposed as the constructor of the singular value decomposition SVD class
U,W,V^T can be obtained as member variables
VではなくV^Tの形式
W is returned in vector form with diagonal components only, not in matrix form
Can be converted to a diagonal matrix with the diag function


ASCII file

Python

def main():
    output=['This is','a pen']
    output=[s+'\n' for s in output]
    with open('text.txt',mode='w') as f:
        f.writelines(output)
    with open('text.txt',mode='r') as f:
        input=f.readlines()
    input=[s.replace('\n','') for s in input]
    print(input)
if __name__=='__main__':
    main()

Output

['This is', 'a pen']

text.txt

This is
a pen

Can open files with the open function
If a file is opened within the with range and goes outside the with range, the file is closed.
Specify whether to read or write the file in the mode of the open function.
The writelines function can output strings in a list.
    Since line feeds are not output, put the line feed code in the list.
readlines function reads all lines of a text file into a list
    If it is disturbing, remove the line feed code.

C++

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
    vector<string> output = { "This is","a pen" };
    ofstream ofs;
    ofs.open("text.txt", ios::out | ios::trunc);
    for (string item : output)ofs << item << endl;
    ofs.close();
    vector<string> input;
    ifstream ifs;
    ifs.open("text.txt", ios::in);
    while (!ifs.eof()) {
        string item;
        getline(ifs, item);
        input.push_back(item);
    }
    ifs.close();
    for (string item : input)cout << item << endl;
    cin.get();
    return 0;
}

Output

This is
a pen

text.txt

This is
a pen

Can open files with the open function
Finally, close the file with the close function
Specify the input or output mode of the file in the argument of the open function.
String in a list can be output by pouring it into an ofstream object.
read all lines of a text file into a list with the getline function


Binary file

Python

import numpy as np
def main():
    output=np.array([[1,2],[3,4],[5,6]],dtype=np.float64)
    with open('binary.bin',mode='wb') as f:
        output.astype(np.float32).tofile(f)
    with open('binary.bin',mode='rb') as f:
        input=np.fromfile(f,dtype=np.float32)
    input=input.astype(np.float64).reshape((3,2))
    print(input)
if __name__=='__main__':
    main()

Output

[[1. 2.]
 [3. 4.]
 [5. 6.]]

binary.bin

00 00 80 3F 00 00 00 40
00 00 40 40 00 00 80 40
00 00 A0 40 00 00 C0 40
という16進数の24バイトのファイル

Raw data of 32-bit floating-point numbers

C++

#include <iostream>
#include <fstream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat output = (Mat_<double>(3, 2) << 1, 2, 3, 4, 5, 6);
    ofstream ofs;
    ofs.open("binary.bin", ios::out | ios::trunc | ios::binary);
    for (int i = 0; i < output.rows; i++) {
        for (int j = 0; j < output.cols; j++) {
            float val;
            val = (float)output.at<double>(i, j);
            ofs.write((char*)&val, sizeof(float));
        }
    }
    ofs.close();
    Mat input = Mat::zeros(3, 2, CV_64F);
    ifstream ifs;
    ifs.open("binary.bin", ios::in | ios::binary);
    for (int i = 0; i < input.rows; i++) {
        for (int j = 0; j < input.cols; j++) {
            float val;
            ifs.read((char*)&val, sizeof(float));
            input.at<double>(i, j) = val;
        }
    }
    ifs.close();
    cout << input << endl;
    cin.get();
    return 0;
}

Output

[1, 2;
 3, 4;
 5, 6]

binary.bin

00 00 80 3F 00 00 00 40
00 00 40 40 00 00 80 40
00 00 A0 40 00 00 C0 40
という16進数の24バイトのファイル

Raw data of 32-bit floating-point numbers


numpy matrix file

Python

import numpy as np
def main():
    output=np.array([[1,2],[3,4],[5,6]],dtype=np.float64)
    np.save('datafile',output)
    input=np.load('datafile.npy')
    print(input)
if __name__=='__main__':
    main()

Output

[[1. 2.]
 [3. 4.]
 [5. 6.]]

Output file

datafile.npy

Use load/save functions for input/output in the form of a numpy matrix file
Basically no other programming language can read/write numpy matrix files


Directory

Python

import os
def main():
    if os.path.exists('directory'):
        print('既にあります')
    else:
        print('ディレクトリを作成します')
        os.mkdir('directory')
if __name__=='__main__':
    main()

Output

ディレクトリを作成します

Created directory

directory

It is possible to check if the directory exists by using path exists in os.
Directories can be created with mkdir in os.

C++

#include <iostream>
#include <filesystem>
using namespace std;
int main(int argc, char** argv)
{
    if (filesystem::exists("directory")) {
        cout << "既にあります" << endl;
    }
    else {
        cout << "ディレクトリを作成します" << endl;
        filesystem::create_directory("directory");
    }
    cin.get();
    return 0;
}

Output

ディレクトリを作成します

Created directory

directory

The existence of a directory can be checked with filesystem exists.
Directories can be created with create_directory in the filesystem.
Because filesystem is a relatively new C++ feature, it cannot be used with some compilers.
If filesystem is not available, use functions in sys/stat.h or direct.h


Monochrome image

Python

import cv2
def main():
    input=cv2.imread('input.bmp',cv2.IMREAD_GRAYSCALE)
    if input is None:
        print('ファイルを読み込めません')
        return
    rows,cols=input.shape
    output=input.copy()
    for y in range(0,rows):
        for x in range(0,cols):
            sum=0
            num=0
            for yy in range(y-1,y+2):
                for xx in range(x-1,x+2):
                    if yy>=0 and xx>=0 and yy<rows and xx<cols:
                        sum+=input[yy,xx]
                        num+=1
            output[y,x]=sum/num
    cv2.imwrite('output.bmp',output)
    cv2.imshow('OpenCV program', output)
    cv2.waitKey()
    cv2.destroyAllWindows()
if __name__=='__main__':
    main()

Sample source code that reads an image, performs some processing, and outputs the image
Specify the name of the image file to be read into the imread function and whether it should be read as grayscale or color.
shape gives the number of rows and columns in the image
Pixel (x,y) data in a monochrome image is specified by [y,x] subscripts
RGB of color image is specified by [y,x,2],[y,x,1],[y,x,0] subscripts
imwrite to output image file, imshow to display image in window, waitKey to wait until key is pressed, destroyAllWindows to close window

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat input = imread("input.bmp", IMREAD_GRAYSCALE);
    if (input.empty()) {
        cout << "ファイルを読み込めません" << endl;
        return 1;
    }
    Mat output = input.clone();
    for (int y = 0; y < input.rows; y++) {
        for (int x = 0; x < input.cols; x++) {
            double sum = 0.0;
            int num = 0;
            for (int yy = y - 1; yy <= y + 1; yy++) {
                for (int xx = x - 1; xx <= x + 1; xx++) {
                    if (yy >= 0 && xx >= 0 && yy < input.rows && xx < input.cols) {
                        sum += (double)input.at<unsigned char>(yy, xx);
                        num++;
                    }
                }
            }
            output.at<unsigned char>(y, x) = (unsigned char)(sum / (double)num);
        }
    }
    imwrite("output.bmp", output);
    imshow("OpenCV program", output);
    waitKey();
    destroyAllWindows();
    return 0;
}

Sample source code that reads an image, performs some processing, and outputs the image
Specify the name of the image file to be read into the imread function and whether it should be read as grayscale or color.
rows and cols gives the number of rows and columns in the image
The data of pixel (x,y) in a monochrome image is specified by at<uchar>(y,x)
RGB of color image is specified by at<Vec3b>(y,x)[2], at<Vec3b>(y,x)[1], at<Vec3b>(y,x)[0]
    Vec3b is a type that represents a 3-channel uchar
imwrite to output image file, imshow to display image in window, waitKey to wait until key is pressed, destroyAllWindows to close window


Color image

Python

import cv2
def main():
    input=cv2.imread('input.bmp',cv2.IMREAD_COLOR)
    if input is None:
        print('ファイルを読み込めません')
        return
    rows,cols,_=input.shape
    output=input.copy()
    for y in range(0,rows):
        for x in range(0,cols):
            r=input[y,x,2]
            g=input[y,x,1]
            b=input[y,x,0]
            output[y,x,2]=0.9*r
            output[y,x,1]=0.7*g
            output[y,x,0]=0.4*b
    cv2.imwrite('output.bmp',output)
    cv2.imshow('OpenCV program', output)
    cv2.waitKey()
    cv2.destroyAllWindows()
if __name__=='__main__':
    main()

Sample source code that reads an image, performs some processing, and outputs the image
Specify the name of the image file to be read into the imread function and whether it should be read as grayscale or color.
shape gives the number of rows and columns in the image
Pixel (x,y) data in a monochrome image is specified by [y,x] subscripts
RGB of color image is specified by [y,x,2],[y,x,1],[y,x,0] subscripts
imwrite to output image file, imshow to display image in window, waitKey to wait until key is pressed, destroyAllWindows to close window

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat input = imread("input.bmp", IMREAD_COLOR);
    if (input.empty()) {
        cout << "ファイルを読み込めません" << endl;
        return 1;
    }
    Mat output = input.clone();
    for (int y = 0; y < input.rows; y++) {
        for (int x = 0; x < input.cols; x++) {
            unsigned char r = input.at<Vec3b>(y, x)[2];
            unsigned char g = input.at<Vec3b>(y, x)[1];
            unsigned char b = input.at<Vec3b>(y, x)[0];
            output.at<Vec3b>(y, x)[2] = (unsigned char)(0.9 * (double)r);
            output.at<Vec3b>(y, x)[1] = (unsigned char)(0.7 * (double)g);
            output.at<Vec3b>(y, x)[0] = (unsigned char)(0.4 * (double)b);
        }
    }
    imwrite("output.bmp", output);
    imshow("OpenCV program", output);
    waitKey();
    destroyAllWindows();
    return 0;
}

Sample source code that reads an image, performs some processing, and outputs the image
Specify the name of the image file to be read into the imread function and whether it should be read as grayscale or color.
rows and cols gives the number of rows and columns in the image
The data of pixel (x,y) in a monochrome image is specified by at<uchar>(y,x)
RGB of color image is specified by at<Vec3b>(y,x)[2], at<Vec3b>(y,x)[1], at<Vec3b>(y,x)[0]
    Vec3b is a type that represents a 3-channel uchar
imwrite to output image file, imshow to display image in window, waitKey to wait until key is pressed, destroyAllWindows to close window


merge and split

Python

import numpy as np
import cv2
def main():
    a0=np.array([
        [111,121,131,141,151],
        [211,221,231,241,251],
        [311,321,331,341,351],
        [411,421,431,441,451]],
        dtype=np.int32)
    a1=np.array([
        [112,122,132,142,152],
        [212,222,232,242,252],
        [312,322,332,342,352],
        [412,422,432,442,452]],
        dtype=np.int32)
    a2=np.array([
        [113,123,133,143,153],
        [213,223,233,243,253],
        [313,323,333,343,353],
        [413,423,433,443,453]],
        dtype=np.int32)

    a=cv2.merge((a0,a1,a2))
    print('a=',a)
    print(a.shape)
    b=cv2.split(a)
    print('b0=',b[0])
    print('b1=',b[1])
    print('b2=',b[2])
    print(b[0].shape)

    a=np.stack([a0,a1,a2],axis=2)
    print('a=',a)
    print(a.shape)
    b0=a[:,:,0]
    b1=a[:,:,1]
    b2=a[:,:,2]
    b0=b0.reshape(a.shape[0],a.shape[1])
    b1=b1.reshape(a.shape[0],a.shape[1])
    b2=b2.reshape(a.shape[0],a.shape[1])
    print('b0=',b0)
    print('b1=',b1)
    print('b2=',b2)
    print(b0.shape)

if __name__=='__main__':
    main()

Output

(skipped)
(4, 5, 3)
(skipped)
(4, 5)

merge 3 monochrome images into 1 3-channel image
Make one 3-channel image into three monochrome images with split
You can also use stack to make 3 images into one.
Slicing can make one image into three.

C++

#include <iostream>
using namespace std;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
    Mat aa[3];
    aa[0] = (Mat_<int>(4, 5) <<
        111, 121, 131, 141, 151,
        211, 221, 231, 241, 251,
        311, 321, 331, 341, 351,
        411, 421, 431, 441, 451);
    aa[1] = (Mat_<int>(4, 5) <<
        112, 122, 132, 142, 152,
        212, 222, 232, 242, 252,
        312, 322, 332, 342, 352,
        412, 422, 432, 442, 452);
    aa[2] = (Mat_<int>(4, 5) <<
        113, 123, 133, 143, 153,
        213, 223, 233, 243, 253,
        313, 323, 333, 343, 353,
        413, 423, 433, 443, 453);

    Mat a;
    merge(aa, 3, a);
    cout << "a=" << a << endl;
    cout << a.rows << " " << a.cols << " " << a.channels() << endl;
    Mat b[3];
    split(a, b);
    cout << "b0=" << b[0] << endl;
    cout << "b1=" << b[1] << endl;
    cout << "b2=" << b[2] << endl;
    cout << b[0].rows << " " << b[0].cols << " " << b[0].channels() << endl;

    return 0;
}

Output

(skipped)
4 5 3
(skipped)
4 5 1

merge 3 monochrome images into 1 3-channel image
Make one 3-channel image into three monochrome images with split


Back