SlideShare a Scribd company logo
Basic C++ 11 & 14 for Python
Programmers
Some Common Programming Patterns
July 2017 by pcman@appier
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”]
> {“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/bidders/ai_util.py
Import
import app.bidders.ai_util
Namespace: defined by directory structure
Fully qualified names:
app.bidders.ai_util.func(“xxx”)
C++
Files:
app/bidders/ai_util.hpp & ai_util.cpp
Import:
#include “app/bidders/ai_utils.hpp”
Namespace: not related to directory structure
namespace app {
namespace bidder {
namespace ai_util {
void func(const char* str);
}
}
}
Fully qualified names:
app::bidders::ai_util::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 Raccoon:
def get_name(self):
return ‘raccoon’
class Zebra(Raccoon):
def get_name(self):
return “zebra_” + Raccoon.get_name()
def func(maybe_racoon):
print maybe_racoon.get_name()
obj = Zebra()
func(obj)
> zebra_raccoon
class Raccoon {
public:
std::string getName() const {
return “raccoon”;
}
};
class Zebra: public Raccoon {
public:
std::string getName() const {
return “zebra” + Raccoon::getName();
}
};
void func(const Raccoon& maybeRaccoon) {
std::cout << maybeRaccoon.getName() << std::endl;
}
Zebra obj;
func(obj);
> raccoon 11
Virtual function
class Raccoon:
def get_name(self):
return ‘raccoon’
class Zebra(Raccoon):
def get_name(self):
return “zebra_” + Raccoon.get_name()
def func(maybe_racoon):
print maybe_racoon.get_name()
obj = Zebra()
func(obj)
> zebra_raccoon
class Raccoon {
public:
virtual std::string getName() const {
return “raccoon”;
}
};
class Zebra: public Raccoon {
public:
std::string getName() override const {
return “zebra” + Raccoon::getName();
}
};
void func(const Raccoon& maybeRaccoon) {
std::cout << maybeRaccoon.getName() << std::endl;
}
Zebra obj;
func(obj);
> zebra_raccoon 12
Manage Objects
Python
obj = ObjClass()
obj.method(arg)
obj.attribute = 100
obj2 = obj ← reference the same object
# Manual delete is not neeed
ObjClass* obj = nullptr; ← prefer nullptr over NULL
ObjClass* obj = new ObjClass(); ← allocate on heap
obj->method(arg);
obj->attribuge = 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

[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
Seok-joon Yun
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
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
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
Slawomir Dorzak
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
Egor Bogatov
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider
 
C++11
C++11C++11
Tiramisu概要
Tiramisu概要Tiramisu概要
Tiramisu概要
Mr. Vengineer
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
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
Appier
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensions
Mr. Vengineer
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
Bartlomiej Filipek
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit Testing
Dmitry Vyukov
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
Bartlomiej Filipek
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
Bartlomiej Filipek
 
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
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
Sergey Platonov
 

What's hot (20)

[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
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
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
C++11
C++11C++11
C++11
 
Tiramisu概要
Tiramisu概要Tiramisu概要
Tiramisu概要
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
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
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensions
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit Testing
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 

Similar to Basic c++ 11/14 for python programmers

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
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
Ovidiu Farauanu
 
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
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu
 
C
CC
C
CC
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
 
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
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
C++ Homework Help
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
gkgaur1987
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
Teddy Hsiung
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
Lennart Regebro
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
LogeekNightUkraine
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
jatin batra
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
DevGAMM Conference
 

Similar to Basic c++ 11/14 for python programmers (20)

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
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
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...
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
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...
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 

More from Jen Yee Hong

COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
Jen Yee Hong
 
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
Jen Yee Hong
 
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
Jen Yee Hong
 
TPET8演講: 非典型程式教育
TPET8演講: 非典型程式教育TPET8演講: 非典型程式教育
TPET8演講: 非典型程式教育
Jen Yee Hong
 
2016-04-07-清大-國際化開源專案技術實務與經驗分享
2016-04-07-清大-國際化開源專案技術實務與經驗分享2016-04-07-清大-國際化開源專案技術實務與經驗分享
2016-04-07-清大-國際化開源專案技術實務與經驗分享
Jen Yee Hong
 
Py drum
Py drumPy drum
Py drum
Jen Yee Hong
 
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
Jen Yee Hong
 
Gtk to qt
Gtk to qtGtk to qt
Gtk to qt
Jen Yee Hong
 

More from Jen Yee Hong (8)

COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
COSCUP 2019 國際開放原始碼專案經營 - 從失敗中學習
 
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
PIME - 用 Python 和 JavaScript 快速開發 Windows 的中文輸入法
 
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
COSCUP 2016: 開源軟硬體實做全套電子鼓(python + RPi)
 
TPET8演講: 非典型程式教育
TPET8演講: 非典型程式教育TPET8演講: 非典型程式教育
TPET8演講: 非典型程式教育
 
2016-04-07-清大-國際化開源專案技術實務與經驗分享
2016-04-07-清大-國際化開源專案技術實務與經驗分享2016-04-07-清大-國際化開源專案技術實務與經驗分享
2016-04-07-清大-國際化開源專案技術實務與經驗分享
 
Py drum
Py drumPy drum
Py drum
 
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
 
Gtk to qt
Gtk to qtGtk to qt
Gtk to qt
 

Recently uploaded

Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 

Recently uploaded (20)

Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 

Basic c++ 11/14 for python programmers

  • 1. Basic C++ 11 & 14 for Python Programmers Some Common Programming Patterns July 2017 by pcman@appier
  • 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”] > {“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/bidders/ai_util.py Import import app.bidders.ai_util Namespace: defined by directory structure Fully qualified names: app.bidders.ai_util.func(“xxx”) C++ Files: app/bidders/ai_util.hpp & ai_util.cpp Import: #include “app/bidders/ai_utils.hpp” Namespace: not related to directory structure namespace app { namespace bidder { namespace ai_util { void func(const char* str); } } } Fully qualified names: app::bidders::ai_util::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 Raccoon: def get_name(self): return ‘raccoon’ class Zebra(Raccoon): def get_name(self): return “zebra_” + Raccoon.get_name() def func(maybe_racoon): print maybe_racoon.get_name() obj = Zebra() func(obj) > zebra_raccoon class Raccoon { public: std::string getName() const { return “raccoon”; } }; class Zebra: public Raccoon { public: std::string getName() const { return “zebra” + Raccoon::getName(); } }; void func(const Raccoon& maybeRaccoon) { std::cout << maybeRaccoon.getName() << std::endl; } Zebra obj; func(obj); > raccoon 11
  • 12. Virtual function class Raccoon: def get_name(self): return ‘raccoon’ class Zebra(Raccoon): def get_name(self): return “zebra_” + Raccoon.get_name() def func(maybe_racoon): print maybe_racoon.get_name() obj = Zebra() func(obj) > zebra_raccoon class Raccoon { public: virtual std::string getName() const { return “raccoon”; } }; class Zebra: public Raccoon { public: std::string getName() override const { return “zebra” + Raccoon::getName(); } }; void func(const Raccoon& maybeRaccoon) { std::cout << maybeRaccoon.getName() << std::endl; } Zebra obj; func(obj); > zebra_raccoon 12
  • 13. Manage Objects Python obj = ObjClass() obj.method(arg) obj.attribute = 100 obj2 = obj ← reference the same object # Manual delete is not neeed ObjClass* obj = nullptr; ← prefer nullptr over NULL ObjClass* obj = new ObjClass(); ← allocate on heap obj->method(arg); obj->attribuge = 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