SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

[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
 
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 AutumnMoriyoshi 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 languageSlawomir Dorzak
 
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 / OverviewMarkus Schneider
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeDmitri 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 ProgrammersAppier
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensionsMr. Vengineer
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - OverviewBartlomiej Filipek
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit TestingDmitry 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++17Bartlomiej 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
 

Tendances (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 = ❤️
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 

Similaire à 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 RopeYung-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.pptxssuser3cbb4c
 
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
 
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 HelpC++ Homework Help
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기Ji Hun Kim
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 
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.17LogeekNightUkraine
 
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.docxeugeniadean34240
 
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 Centrejatin batra
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 

Similaire à 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
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 

Plus de 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
 
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)
PIME - 用 Python 快速開發 Windows 的中文輸入法 (COSCUP 2015)Jen Yee Hong
 

Plus de 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
 

Dernier

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Dernier (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

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