SlideShare a Scribd company logo
1
Define Variables
Python
a = 1
b = 0.0
c = ‘xxx’
C++
int a = 1;
auto a = 1;
double b = 0.0;
auto b = 0.0;
const char c[] = “xxx”; // C string (char array)
const char* c = “xxx”; // C string (pointer)
std::string c = “xxx”;
std::string c(“xxx”);
std::string c{“xxx”};
2
Variable Scopes
global_var1 = 1
def func(arg):
local_var = 2
global global_var2
global_var2 = ‘xxx’ ← global
if arg:
local_var2 = 0.5 ← scope: function
…
# if arg evaluates to True,
# local_var2 is still accessible here.
return False
int global_var1 = 1; ← global
static std::string global_var2; ← global in the current file
bool func(bool arg) {
int local_var = 2;
global_var2 = “xxx”;
if(arg) {
double local_var2 = 0.5; ← scope: if block
….
}
// local_var2 is undefined here
}
3
Reference
s1 = {“key1” : 100}
s2 = s1 ← reference the same object
s2[“key2”] = 200
print s1
> {“key1”:100, “key2”: 200}
s2 = {} ← s1 is NOT changed, s1 and s2
reference different objects now
std::unordered_map<std::string, int> s1 = {“key1” : 100};
std::unordered_map<std::string, int> s2 = s1; ← copy the whole
object
std::unordered_map<std::string, int>& s2 = s1; ← reference the
same object
s2 = std::unordered_map<std::string, int>(); ← s1 is changed, s1
and s2 still reference the same object
In C++ 11, use auto
auto s2 = s1; ← copy the whole object (slow)
auto& s2 = s1; ← reference the same object
// Now s2 is a reference to s1, However, ...
auto s3 = s2; ← copy the whole s1 object. s3 is NOT a reference
const auto& s3 = s2; ← reference the same s1 object
4
Reference
a = {“key”: 100}
b = a
b = {“key2”: 200}
std::unordered_map<std::string, int> a = {{“key”, 100}};
auto& b = a;
b = std::unordered_map<std::string, int>{{“key2”, 200}};
5
key: 100a
key: 100a
b
key: 100a
b key2: 200
key: 100a
key: 100
a
b
key2: 200
a
b
Conditional
if a == 1 and b == 2:
pass
elif c == 3 or d == 4:
pass
else:
pass
if a == 1:
…
elif a == 2:
…
elif a == 3:
…
else:
….
If (a == 1 && b == 2) {
}
else if(c == 3 || d == 4) {
}
else {
}
switch(a) {
case 1:
…
break; // without break, will run case 2 as well
case 2: { // create a new scope if we need to define new variables
int a = 100;
break;
}
default: // it’s good practice to always add this
...
};
6
Namespace & Imports
Python:
File: app/my_service/utils.py
Import
import app.my_service.utils
Namespace: defined by directory structure
Fully qualified names:
app.my_service.utils.func(“xxx”)
C++
Files:
app/my_service/utils.hpp & utils.cpp
Import:
#include “app/my_service/utils.hpp”
Namespace: not related to directory structure
namespace app {
namespace my_service {
namespace utils {
void func(const char* str);
}
}
}
Fully qualified names:
app::my_service::utils::func(“xxx”); 7
Loops
for i in xrange(100):
pass
while cond:
….
a = [0, 1, 100]
for item in a:
pass
b = {“key”: 0.5, “key2”, 1.0}
for key, val in b.iteritems():
pass
for(int i = 0; i < 100; ++i) {
...
}
while(cond) {
}
std::vector<int> a = {0, 1, 100};
for(auto& item: a) { // without &, this will copy each item
}
std::unordered_map<std::string, double> b = {{“key”, 0.5}, {“key2”,
1.0}};
for(auto& item: b) { // without &, this will copy each item
auto& key = item.first;
auto& val = item.second;
}
8
Functions
Python:
def func(arg1, arg2):
….
return ret1, ret2, ret3
C++
void func(const Arg1& arg1, const Arg2& arg2, …
Ret1& ret1, Ret2& ret2, Ret3& ret3
) {
…
ret1 = ….;
ret2 = ….;
ret3 = ….;
}
● No multiple return values
● Need to specify the type of the return value
● Every variable needs to have type declaration
● Declaration before use is required
● Add const to the references that are not changed by the
method
● Declare in *.hpp, implement in *.cpp (for public functions)
9
Class Definition
Python version: only one *.py file:
class PythonClass(ParentClass):
def __init__(self):
ParentClass.__init__(self) # python2
self.attrib = 5566
Self.attrib2 = ‘xxx’
def some_method(self, arg1, arg2):
return arg1 * arg2 + self.attrib
def _some_private_method(self):
pass
-------------- Declaration: cpp_class.hpp -----------------------
class CppClass: public ParentClass {
public:
CppClass(): ParentClass(), attrib(5566),
attrib2(“xxx”) {
}
virtual ~CppClass(): {
// destructor: free allocated resources here
}
double someMethod(double arg1, double arg2);
private:
void somePrivateMethod() {}
int attrib;
std::string attrib2;
};
---------------- Implementation: cpp_class.cpp ------------
#include “cpp_class.hpp”
double CppClass::someMethod(double arg1, double arg2) {
return arg1 * arg2 + attrib;
}
10
Virtual function
class BaseType:
def get_name(self):
return ‘base_type’
class DerivedType(BaseType):
def get_name(self):
return “derived_” +
BaseType.get_name()
def func(maybe_base_type):
print maybe_base_type.get_name()
obj = DerivedType()
func(obj)
> derived_base_type
class BaseType {
public:
std::string getName() const {
return “base_type”;
}
};
class DerivedType: public BaseType {
public:
std::string getName() const {
return “derived_” + BaseType::getName();
}
};
void func(const BaseType& maybeBaseType) {
std::cout << maybeBaseType.getName() << std::endl;
}
DerivedType obj;
func(obj);
> base_type 11
Virtual function
class BaseType:
def get_name(self):
return ‘base_type’
class DerivedType(BaseType):
def get_name(self):
return “derived_” +
BaseType.get_name()
def func(maybe_base_type):
print maybe_base_type.get_name()
obj = DerivedType()
func(obj)
> derived_base_type
class BaseType {
public:
virtual std::string getName() const {
return “base_type”;
}
};
class DerivedType: public BaseType {
public:
std::string getName() override const {
return “derived_” + BaseType::getName();
}
};
void func(const BaseType& maybeBaseType) {
std::cout << maybeBaseType.getName() << std::endl;
}
DerivedType obj;
func(obj);
> derived_base_type 12
Manage Objects
Python
obj = ObjClass()
obj.method(arg)
obj.attribute = 100
obj2 = obj ← reference the same object
# Manual delete is not needed
ObjClass* obj = nullptr; ← prefer nullptr over NULL
ObjClass* obj = new ObjClass(); ← allocate on heap
obj->method(arg);
obj->attribute = 100;
auto obj2 = obj; // point to the same object
auto obj2 = *obj; // copy!!!
auto& obj2 = *obj; // reference the same object
delete obj; // when not used, manual delete is required
ObjectClass localObj(); ← allocate on local stack
localObj.method(arg);
Raw pointer is not recommended. Use smart pointers
#include <memory>
std::shared_ptr<ObjClass> obj;
auto obj = std::make_shared<ObjClass>();
obj->method(arg);
obj->attribute = 100; // manual delete is not needed
auto obj2 = obj; ← point to the same object (no * or &)
13
Common Data Types (Python → C++)
● int:
○ int, long, unsigned int, unsigned long (size is architecture dependent)
○ std::int64_t, std::uint64_t, std::int16_t, ... (#include <cstdint>, well-defined sizes)
● bool: bool
● float: double (64-bit), float(32-bit, bad performance & not recommended)
● str, bytes: std::string (#include <string>)
● containers:
○ list: std::vector<> (#include <vector>)
○ dict: std::unordered_map<> (#include <unordered_map>)
○ set: std::unordered_set<> (#include <unordered_set>)
● None:
○ For float, can use NAN (#include <cmath>) and use std::isnan(number) to check if it’s NAN
○ For string, just use empty string and use str.empty() to check if it’s empty
14
Define Strings
s = “this is a string”
s2 = s → s2 and s reference the same object
len(s)
t = “prefix_’ + s + ‘_suffix’
t = “prefix1” + “prefix2” + s
s = “has0zero”
len(s): 8
#include <string>
std::string s = “this is a string”;
auto s2 = s; ← copy s to s2 (new object)
auto& s2 = s; ← s2 is a reference only
s.length();
auto t = “prefix_” + s + “_suffix”; ← works but slower
std::string t = “prefix_”; t += s; t += “_suffix”; ← good
auto t = “prefix1” + “prefix2” + s; ← does not work
std::string s = “has0zero”; ← incorrect
s.length(): 3
std::string s(“has0zero”, 8); ← correct
Alternative (C++ 14):
using namespace std::string_literals;
auto z = “has0zero”s; ← add “s” suffix, z is std::string
auto z = “has0zero”; ← z is char* pointer
15
String Methods
t = “test str”
if t.find(“sub_str”) == -1:
print “not found”
u = t[1:2]; # get sub string
u = t[2:]; # get sub string til end
if not t:
print “empty str”
v = t.lower()
#include <string>
std::string t = “test str”;
if (t.find(“sub_str”) == std::string::npos)
std::cout << “not foundn”;
if( t.empty())
std::cout << “empty strn”;
auto u = t.substr(1, 2);
auto u = t.substr(1);
#include <algorithm>
#include <cctype>
std::transform(t.begin(), t.end(), t.begin(), std::tolower);
(This does not work in unicode, C++ sucks!)
16
List (dynamic array)
Python
a = [1, 2, 3]
b = [“str1”, “str2”, “str3”]
c = [“xxx”, {}, 100, 0.5] → cannot be done in C++
a.append(100)
a.insert(2, 10)
del a[1]
del a[0:2]
tmp = a[0:2]
tmp = a[2]
tmp2 = b[1] ← reference the element
C++
#include <vector>
std::vector<int> a = {1, 2, 3};
std::vector<std::string> b = {“str1”, “str2”, “str3”};
std::vector<????> c ← cannot be done in C++
a.push_back(100);
a.insert(a.begin() + 2, 10);
a.erase(a.begin() + 1);
a.erase(a.begin(), a.begin() + 2);
std::vector<int> tmp{a.begin(), a.begin() + 2};
auto tmp = a[2];
auto tmp2 = b[1]; ← copy the element!
auto& tmp2 = b[1]; ← reference the element
17
Set
Python
a = set()
a = {“1”, “2”, “3”}
b = [1, 2, 3]
c = set(b)
a.add(“x”)
a.remove(“2”)
if “4” in a:
pass
C++
#include <unordered_set>
std::unordered_set<std::string> a;
std::unordered_set<std::string> a = {“1”, “2”, “3”};
std::vector<int> b = {1, 2, 3};
std::unordered_set<int> c(b.begin(), b.end());
a.insert(“x”);
a.erase(“2”);
if (a.find(“4”) != a.end()) {
...
}
18
Dict
Python
d = {“a”: 1, “b”: 2}
nested = {
“a”: {“a1”: 0.5},
“b”: {“b1”: 0.3, “b2”: 0.4},
}
free = {“a”: 100, “b”: “xxx”, 50: None} ← No! you
cannot do this in C++
d = defaultdict(lambda: “null”); ← You cannot do
this in C++ (easily)
C++
#include <unordered_map>
std::unordered_map<std::string, int> d = {
{“a”, 1}, {“b”, 2}
};
std::unordered_map<std::string,
std::unordered_map<std::string, int>> nested = {
{“a”: {{“a1”, 0.5}}},
{“b”: {{“b1”, 0.3}, {“b2”, 0.4}},
};
19
Common Dict Operations
Python
d[“new_key”] = 100
d[“no such key”] → raise KeyError
del d[“key”];
if “key” in d:
e = d[“key”]
for key, val in d.iteritems():
pass
C++
d[“new_key”] = 100;
d[“no such key”] → create a new item for it
d.erase(“key”);
auto iter = d.find(“key”);
if(iter != d.end()) {
// without &, this will do copy
auto& e = iter->second;
}
// C++ 11 ranged for loop syntax
for(auto& item: d) { // without &, this will do copy
auto& key = item.first;
auto& val = item.second;
...
} 20

More Related Content

What's hot

Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
Egor Bogatov
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
Anton Bikineev
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
corehard_by
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
DevGAMM Conference
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)changehee lee
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
Sergey Platonov
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
corehard_by
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in Golang
Dan Tran
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
Andrey Karpov
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
Chris Ohk
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime
 
C programs
C programsC programs
C programs
Vikram Nandini
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
Ingvar Stepanyan
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 

What's hot (20)

Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Groovy
GroovyGroovy
Groovy
 
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in Golang
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
 
C programs
C programsC programs
C programs
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 

Similar to Basic C++ 11/14 for Python Programmers

Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
Jen Yee Hong
 
C++11
C++11C++11
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
Ovidiu Farauanu
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
Akira Maruoka
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
C++ Homework Help
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
Lennart Regebro
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
Linaro
 
Lecture5
Lecture5Lecture5
Lecture5
Sunil Gupta
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
IO redirection in C shellPlease implement input output redirect.pdf
IO redirection in C shellPlease implement input  output redirect.pdfIO redirection in C shellPlease implement input  output redirect.pdf
IO redirection in C shellPlease implement input output redirect.pdf
forecastfashions
 

Similar to Basic C++ 11/14 for Python Programmers (20)

Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
C++11
C++11C++11
C++11
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
IO redirection in C shellPlease implement input output redirect.pdf
IO redirection in C shellPlease implement input  output redirect.pdfIO redirection in C shellPlease implement input  output redirect.pdf
IO redirection in C shellPlease implement input output redirect.pdf
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 

Basic C++ 11/14 for Python Programmers

  • 1. 1
  • 2. Define Variables Python a = 1 b = 0.0 c = ‘xxx’ C++ int a = 1; auto a = 1; double b = 0.0; auto b = 0.0; const char c[] = “xxx”; // C string (char array) const char* c = “xxx”; // C string (pointer) std::string c = “xxx”; std::string c(“xxx”); std::string c{“xxx”}; 2
  • 3. Variable Scopes global_var1 = 1 def func(arg): local_var = 2 global global_var2 global_var2 = ‘xxx’ ← global if arg: local_var2 = 0.5 ← scope: function … # if arg evaluates to True, # local_var2 is still accessible here. return False int global_var1 = 1; ← global static std::string global_var2; ← global in the current file bool func(bool arg) { int local_var = 2; global_var2 = “xxx”; if(arg) { double local_var2 = 0.5; ← scope: if block …. } // local_var2 is undefined here } 3
  • 4. Reference s1 = {“key1” : 100} s2 = s1 ← reference the same object s2[“key2”] = 200 print s1 > {“key1”:100, “key2”: 200} s2 = {} ← s1 is NOT changed, s1 and s2 reference different objects now std::unordered_map<std::string, int> s1 = {“key1” : 100}; std::unordered_map<std::string, int> s2 = s1; ← copy the whole object std::unordered_map<std::string, int>& s2 = s1; ← reference the same object s2 = std::unordered_map<std::string, int>(); ← s1 is changed, s1 and s2 still reference the same object In C++ 11, use auto auto s2 = s1; ← copy the whole object (slow) auto& s2 = s1; ← reference the same object // Now s2 is a reference to s1, However, ... auto s3 = s2; ← copy the whole s1 object. s3 is NOT a reference const auto& s3 = s2; ← reference the same s1 object 4
  • 5. Reference a = {“key”: 100} b = a b = {“key2”: 200} std::unordered_map<std::string, int> a = {{“key”, 100}}; auto& b = a; b = std::unordered_map<std::string, int>{{“key2”, 200}}; 5 key: 100a key: 100a b key: 100a b key2: 200 key: 100a key: 100 a b key2: 200 a b
  • 6. Conditional if a == 1 and b == 2: pass elif c == 3 or d == 4: pass else: pass if a == 1: … elif a == 2: … elif a == 3: … else: …. If (a == 1 && b == 2) { } else if(c == 3 || d == 4) { } else { } switch(a) { case 1: … break; // without break, will run case 2 as well case 2: { // create a new scope if we need to define new variables int a = 100; break; } default: // it’s good practice to always add this ... }; 6
  • 7. Namespace & Imports Python: File: app/my_service/utils.py Import import app.my_service.utils Namespace: defined by directory structure Fully qualified names: app.my_service.utils.func(“xxx”) C++ Files: app/my_service/utils.hpp & utils.cpp Import: #include “app/my_service/utils.hpp” Namespace: not related to directory structure namespace app { namespace my_service { namespace utils { void func(const char* str); } } } Fully qualified names: app::my_service::utils::func(“xxx”); 7
  • 8. Loops for i in xrange(100): pass while cond: …. a = [0, 1, 100] for item in a: pass b = {“key”: 0.5, “key2”, 1.0} for key, val in b.iteritems(): pass for(int i = 0; i < 100; ++i) { ... } while(cond) { } std::vector<int> a = {0, 1, 100}; for(auto& item: a) { // without &, this will copy each item } std::unordered_map<std::string, double> b = {{“key”, 0.5}, {“key2”, 1.0}}; for(auto& item: b) { // without &, this will copy each item auto& key = item.first; auto& val = item.second; } 8
  • 9. Functions Python: def func(arg1, arg2): …. return ret1, ret2, ret3 C++ void func(const Arg1& arg1, const Arg2& arg2, … Ret1& ret1, Ret2& ret2, Ret3& ret3 ) { … ret1 = ….; ret2 = ….; ret3 = ….; } ● No multiple return values ● Need to specify the type of the return value ● Every variable needs to have type declaration ● Declaration before use is required ● Add const to the references that are not changed by the method ● Declare in *.hpp, implement in *.cpp (for public functions) 9
  • 10. Class Definition Python version: only one *.py file: class PythonClass(ParentClass): def __init__(self): ParentClass.__init__(self) # python2 self.attrib = 5566 Self.attrib2 = ‘xxx’ def some_method(self, arg1, arg2): return arg1 * arg2 + self.attrib def _some_private_method(self): pass -------------- Declaration: cpp_class.hpp ----------------------- class CppClass: public ParentClass { public: CppClass(): ParentClass(), attrib(5566), attrib2(“xxx”) { } virtual ~CppClass(): { // destructor: free allocated resources here } double someMethod(double arg1, double arg2); private: void somePrivateMethod() {} int attrib; std::string attrib2; }; ---------------- Implementation: cpp_class.cpp ------------ #include “cpp_class.hpp” double CppClass::someMethod(double arg1, double arg2) { return arg1 * arg2 + attrib; } 10
  • 11. Virtual function class BaseType: def get_name(self): return ‘base_type’ class DerivedType(BaseType): def get_name(self): return “derived_” + BaseType.get_name() def func(maybe_base_type): print maybe_base_type.get_name() obj = DerivedType() func(obj) > derived_base_type class BaseType { public: std::string getName() const { return “base_type”; } }; class DerivedType: public BaseType { public: std::string getName() const { return “derived_” + BaseType::getName(); } }; void func(const BaseType& maybeBaseType) { std::cout << maybeBaseType.getName() << std::endl; } DerivedType obj; func(obj); > base_type 11
  • 12. Virtual function class BaseType: def get_name(self): return ‘base_type’ class DerivedType(BaseType): def get_name(self): return “derived_” + BaseType.get_name() def func(maybe_base_type): print maybe_base_type.get_name() obj = DerivedType() func(obj) > derived_base_type class BaseType { public: virtual std::string getName() const { return “base_type”; } }; class DerivedType: public BaseType { public: std::string getName() override const { return “derived_” + BaseType::getName(); } }; void func(const BaseType& maybeBaseType) { std::cout << maybeBaseType.getName() << std::endl; } DerivedType obj; func(obj); > derived_base_type 12
  • 13. Manage Objects Python obj = ObjClass() obj.method(arg) obj.attribute = 100 obj2 = obj ← reference the same object # Manual delete is not needed ObjClass* obj = nullptr; ← prefer nullptr over NULL ObjClass* obj = new ObjClass(); ← allocate on heap obj->method(arg); obj->attribute = 100; auto obj2 = obj; // point to the same object auto obj2 = *obj; // copy!!! auto& obj2 = *obj; // reference the same object delete obj; // when not used, manual delete is required ObjectClass localObj(); ← allocate on local stack localObj.method(arg); Raw pointer is not recommended. Use smart pointers #include <memory> std::shared_ptr<ObjClass> obj; auto obj = std::make_shared<ObjClass>(); obj->method(arg); obj->attribute = 100; // manual delete is not needed auto obj2 = obj; ← point to the same object (no * or &) 13
  • 14. Common Data Types (Python → C++) ● int: ○ int, long, unsigned int, unsigned long (size is architecture dependent) ○ std::int64_t, std::uint64_t, std::int16_t, ... (#include <cstdint>, well-defined sizes) ● bool: bool ● float: double (64-bit), float(32-bit, bad performance & not recommended) ● str, bytes: std::string (#include <string>) ● containers: ○ list: std::vector<> (#include <vector>) ○ dict: std::unordered_map<> (#include <unordered_map>) ○ set: std::unordered_set<> (#include <unordered_set>) ● None: ○ For float, can use NAN (#include <cmath>) and use std::isnan(number) to check if it’s NAN ○ For string, just use empty string and use str.empty() to check if it’s empty 14
  • 15. Define Strings s = “this is a string” s2 = s → s2 and s reference the same object len(s) t = “prefix_’ + s + ‘_suffix’ t = “prefix1” + “prefix2” + s s = “has0zero” len(s): 8 #include <string> std::string s = “this is a string”; auto s2 = s; ← copy s to s2 (new object) auto& s2 = s; ← s2 is a reference only s.length(); auto t = “prefix_” + s + “_suffix”; ← works but slower std::string t = “prefix_”; t += s; t += “_suffix”; ← good auto t = “prefix1” + “prefix2” + s; ← does not work std::string s = “has0zero”; ← incorrect s.length(): 3 std::string s(“has0zero”, 8); ← correct Alternative (C++ 14): using namespace std::string_literals; auto z = “has0zero”s; ← add “s” suffix, z is std::string auto z = “has0zero”; ← z is char* pointer 15
  • 16. String Methods t = “test str” if t.find(“sub_str”) == -1: print “not found” u = t[1:2]; # get sub string u = t[2:]; # get sub string til end if not t: print “empty str” v = t.lower() #include <string> std::string t = “test str”; if (t.find(“sub_str”) == std::string::npos) std::cout << “not foundn”; if( t.empty()) std::cout << “empty strn”; auto u = t.substr(1, 2); auto u = t.substr(1); #include <algorithm> #include <cctype> std::transform(t.begin(), t.end(), t.begin(), std::tolower); (This does not work in unicode, C++ sucks!) 16
  • 17. List (dynamic array) Python a = [1, 2, 3] b = [“str1”, “str2”, “str3”] c = [“xxx”, {}, 100, 0.5] → cannot be done in C++ a.append(100) a.insert(2, 10) del a[1] del a[0:2] tmp = a[0:2] tmp = a[2] tmp2 = b[1] ← reference the element C++ #include <vector> std::vector<int> a = {1, 2, 3}; std::vector<std::string> b = {“str1”, “str2”, “str3”}; std::vector<????> c ← cannot be done in C++ a.push_back(100); a.insert(a.begin() + 2, 10); a.erase(a.begin() + 1); a.erase(a.begin(), a.begin() + 2); std::vector<int> tmp{a.begin(), a.begin() + 2}; auto tmp = a[2]; auto tmp2 = b[1]; ← copy the element! auto& tmp2 = b[1]; ← reference the element 17
  • 18. Set Python a = set() a = {“1”, “2”, “3”} b = [1, 2, 3] c = set(b) a.add(“x”) a.remove(“2”) if “4” in a: pass C++ #include <unordered_set> std::unordered_set<std::string> a; std::unordered_set<std::string> a = {“1”, “2”, “3”}; std::vector<int> b = {1, 2, 3}; std::unordered_set<int> c(b.begin(), b.end()); a.insert(“x”); a.erase(“2”); if (a.find(“4”) != a.end()) { ... } 18
  • 19. Dict Python d = {“a”: 1, “b”: 2} nested = { “a”: {“a1”: 0.5}, “b”: {“b1”: 0.3, “b2”: 0.4}, } free = {“a”: 100, “b”: “xxx”, 50: None} ← No! you cannot do this in C++ d = defaultdict(lambda: “null”); ← You cannot do this in C++ (easily) C++ #include <unordered_map> std::unordered_map<std::string, int> d = { {“a”, 1}, {“b”, 2} }; std::unordered_map<std::string, std::unordered_map<std::string, int>> nested = { {“a”: {{“a1”, 0.5}}}, {“b”: {{“b1”, 0.3}, {“b2”, 0.4}}, }; 19
  • 20. Common Dict Operations Python d[“new_key”] = 100 d[“no such key”] → raise KeyError del d[“key”]; if “key” in d: e = d[“key”] for key, val in d.iteritems(): pass C++ d[“new_key”] = 100; d[“no such key”] → create a new item for it d.erase(“key”); auto iter = d.find(“key”); if(iter != d.end()) { // without &, this will do copy auto& e = iter->second; } // C++ 11 ranged for loop syntax for(auto& item: d) { // without &, this will do copy auto& key = item.first; auto& val = item.second; ... } 20