Our new blog post featuring some common python programming patterns and their C++ equivalents is now up!
Leave us a comment below and let us know what you'd like to see covered in our future posts!
█ Read More
Technical Insights: Introduction to GraphQL|goo.gl/d7PyXH
2018 cosup-delete unused python code safely - englishJen Yee Hong
The talk is about doing cleanup and refactor for legacy Python code base in a safer way. I introduced several existing tools for this task and demonstrated how (surprisingly) Python ast module can also help in this case.
中文摘要:
不管是 open source 專案還是工作上,經過長時間開發累積,source code 內可能會殘留許多不再需要的 code,造成維護以及 refactor 的困難,也造成新手 trace code 時的障礙。
對 C/C++ 這類編譯式語言來說,開啟編譯器最佳化能自動清除 dead code,但對於 Python 這類動態語言,則沒有公認完美的方法。
本議程分享一些相關經驗,佐以利用 Python AST 的簡易自製工具,討論如何從較複雜的 python source tree 中,安全的清除不再需要的 code。
Code: https://github.com/PCMan/python-find-unused-func
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
The talk will look at limitations of compilers when creating fast code and how to make more effective use of both the underlying micro-architecture of modern CPU's and how algorithmic optimizations may have surprising effects on the generated code. We shall discuss several specific CPU architecture features and their pros and cons in relation to creating fast C++ code. We then expand with several algorithmic techniques, not usually well-documented, for making faster, compiler friendly, C++.
Note that we shall not discuss caching and related issues here as they are well documented elsewhere.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
2018 cosup-delete unused python code safely - englishJen Yee Hong
The talk is about doing cleanup and refactor for legacy Python code base in a safer way. I introduced several existing tools for this task and demonstrated how (surprisingly) Python ast module can also help in this case.
中文摘要:
不管是 open source 專案還是工作上,經過長時間開發累積,source code 內可能會殘留許多不再需要的 code,造成維護以及 refactor 的困難,也造成新手 trace code 時的障礙。
對 C/C++ 這類編譯式語言來說,開啟編譯器最佳化能自動清除 dead code,但對於 Python 這類動態語言,則沒有公認完美的方法。
本議程分享一些相關經驗,佐以利用 Python AST 的簡易自製工具,討論如何從較複雜的 python source tree 中,安全的清除不再需要的 code。
Code: https://github.com/PCMan/python-find-unused-func
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
The talk will look at limitations of compilers when creating fast code and how to make more effective use of both the underlying micro-architecture of modern CPU's and how algorithmic optimizations may have surprising effects on the generated code. We shall discuss several specific CPU architecture features and their pros and cons in relation to creating fast C++ code. We then expand with several algorithmic techniques, not usually well-documented, for making faster, compiler friendly, C++.
Note that we shall not discuss caching and related issues here as they are well documented elsewhere.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
Один из лучших способов снизить количество багов в играх – это показывать программистам, как не стоит писать код. В своём докладе я соберу самые вкусные и необычные ошибки, которые удалось найти в C++ и C# коде таких игр, как VVVVVV, Space Engineers, Command & Conquer, osu! и даже Doom. Я уверен, что каждый из слушателей обязательно узнает для себя что-то новое. В конце концов, это просто приятно – лично увидеть ошибки из кода знакомой и любимой игры!
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
To let the world know about our product, we check open-source projects. By the moment we have checked 245 projects. A side effect: we found 9574 errors and notified the authors about them.
Presentation I gave at a Rust Austin meetup in November 2018 about exploring different approaches for interpreting custom DSLs in Rust with varying speed characteristics and associated safety issues.
Basic c++ 11/14 for python programmersJen Yee Hong
A short list of some common python programming patterns and their C++ equivalents. This can help programmers learn C++ in a more efficient way if he or she already knows Python.
Part of this material is used for internal training of Appier Inc, one of the leading artificial intelligence company in Asia.
Thank Appier Inc. for allowing me to share this.
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
Один из лучших способов снизить количество багов в играх – это показывать программистам, как не стоит писать код. В своём докладе я соберу самые вкусные и необычные ошибки, которые удалось найти в C++ и C# коде таких игр, как VVVVVV, Space Engineers, Command & Conquer, osu! и даже Doom. Я уверен, что каждый из слушателей обязательно узнает для себя что-то новое. В конце концов, это просто приятно – лично увидеть ошибки из кода знакомой и любимой игры!
Как работает LLVM бэкенд в C#. Егор Богатов ➠ CoreHard Autumn 2019corehard_by
LLVM содержит огромное количество оптимизаций и подходит в качестве бэкенда для многих языков программирования. Но все немного усложняется для Managed языков и JIT сценариев. В этом докладе Егор расскажет о трудностях, с которыми столкнулись в C# при реализации LLVM бэкенда.
A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
To let the world know about our product, we check open-source projects. By the moment we have checked 245 projects. A side effect: we found 9574 errors and notified the authors about them.
Presentation I gave at a Rust Austin meetup in November 2018 about exploring different approaches for interpreting custom DSLs in Rust with varying speed characteristics and associated safety issues.
Basic c++ 11/14 for python programmersJen Yee Hong
A short list of some common python programming patterns and their C++ equivalents. This can help programmers learn C++ in a more efficient way if he or she already knows Python.
Part of this material is used for internal training of Appier Inc, one of the leading artificial intelligence company in Asia.
Thank Appier Inc. for allowing me to share this.
Despite being a slow interpreter, Python is a key component in high-performance computing (HPC). Python is easy to use. C++ is fast. Together they are a beautiful blend. A new tool, pybind11, makes this approach even more attractive to HPC code. It focuses on the niceties C++11 brings in. Beyond the syntactic sugar around the Python C API, it is interesting to see how pybind11 handles the vast difference between the two languages, and what matters to HPC.
Razvan Rotari shows an experiment to see how far you can go with binding in C++; Cristian Neamtu follows with an insight on how to achieve this in Rust using Serde.
I am Moffat K. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from London, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++ Programming.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
Compilers such as GCC may use undefined behaviour in language specifications to generate efficient code (especially newer recent versions). The rules for undefined behaviour can be subtle and programming mistakes can lead to correctness and/or security issues. This presentation will examine issues resulting from undefined behavior in applications. It will also discuss the position of the relevant language standards and address what compilers can do to exploit the standard in order to generate optimized code. We will also look at tools that can help us in detecting undefined behaviours so that these correctness issues can be prevented.
IO redirection in C shellPlease implement input output redirect.pdfforecastfashions
I/O redirection in C shell
Please implement input / output redirection in the code posted below. Here are the specs:
Your shell will need to support file redirection. Use the same syntax as defined in the Bash shell:
a single \'>\' implies that one needs to redirect the standard output of the program being started to
the referenced file while a single \'<\' implies the same with standard input. The double \'>>\'
implies that standard output will append to an existing file rather than create a new file (similar
behavior is required for the \'<<\' operator and standard input). You do not need to implement
support for the Bash pipeline operator \'|\'.
Before calling exec to begin execution, the child process may have to close stdin (file desriptor
0) and/or stdout (file descriptor 0), open the corresponding file and use the dup2 system call to
make it the appropriate file descriptor. Don\'t forget to use the close system call to close the old
file descriptor.
#include
#include
#include
#include
#include
#include
using namespace std;
int change_dir(char* args[])
{
if (args[1] == NULL)
{
chdir(getenv(\"HOME\"));
return 1;
}
else
{
if (chdir(args[1]) == -1)
{
cout << \"No such directory\" << args[1];
return -1;
}
}
return 0;
}
int helper_func(char* args[])
{
cout << \"Builtin commands so far are; cd, and help.\ \";
return 0;
}
int main()
{
while(true)
{
cout << \"$ \";
char cmd[128];
cin.getline(cmd,128);
vector args;
char *line = strtok(cmd, \" \");
char *tmp = line;
while (tmp != NULL)
{
args.push_back(tmp);
tmp = strtok(NULL, \" \");
}
char** argv = new char*[args.size() + 1];
for (int i = 0; i < args.size(); i++)
argv[i] = args[i];
argv[args.size()] = NULL;
if (strcmp(cmd, \"exit\") == 0)
{
{
exit(0);
}
}
//else if (strcmp(args[0], \"cd\") == 0) change_dir(args);
if (strcmp(cmd, \"cd\") == 0)
{
change_dir(argv);
}
if (strcmp(cmd, \"help\") == 0)
{
helper_func(argv);
}
else
{
pid_t pid;
pid_t wpid;
int status;
pid = fork();
if (pid == 0)
{
if (execvp(args[0], argv) == -1)
{
perror(\"cmd\");
}
exit(EXIT_FAILURE);
}
else if (pid < 0)
{
perror(\"cmd\");
}
{
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
}
signal(SIGINT, SIG_IGN);
signal(SIGTERM, SIG_DFL);
return 0;
}
Solution
#include
#include
#include
#include
#include
#include
using namespace std;
int change_dir(char* args[])
{
if (args[1] == NULL)
{
chdir(getenv(\"HOME\"));
return 1;
}
else
{
if (chdir(args[1]) == -1)
{
cout << \"No such directory\" << args[1];
return -1;
}
}
return 0;
}
int helper_func(char* args[])
{
cout << \"Builtin commands so far are; cd, and help.\ \";
return 0;
}
int main()
{
while(true)
{
cout << \"$ \";
char cmd[128];
cin.getline(cmd,128);
vector args;
char *line = strtok(cmd, \" \");
char *tmp = line;
while (tmp != NULL)
{
args.push_back(tmp);
tmp = strtok(NULL, \" \");
}
char** argv = new char*[args.size() + 1];
for (int i = 0; i < args.size(); i++)
argv[i] = args[i];
argv[args.size()] = NULL;
if (strcmp(cmd, \.
Similar to Basic C++ 11/14 for Python Programmers (20)
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
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
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