An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
This set of slides introduces the reader to a subset of the C++ Standard Library called the Standard Template Library (STL). The STL provides a collection of parameterized containers and algorithms, and it is the most successful example of an approach to programming called generic programming. In this presentation, we aim at studying the ideals and concepts of the STL by re-implementing small parts of the library. Specifically, we first show how we can discover requirements on types in order to devise generic algorithms. Then, we focus on how to make algorithms independent of containers through the pivotal abstraction of iterators. To this end, we replicate the standard algorithm for finding the minimum in a sequence (min_element), which we subsequently match with a custom forward iterator over intrusive linked lists of integers. Finally, we see how function objects can be used to customize containers and algorithms alike. This allows us to deepen our understanding of ordering relations, and, in particular, to introduce the concept of strict weak orderings.
This set of slides introduces the reader to a subset of the C++ Standard Library called the Standard Template Library (STL). The STL provides a collection of parameterized containers and algorithms, and it is the most successful example of an approach to programming called generic programming. In this presentation, we aim at studying the ideals and concepts of the STL by re-implementing small parts of the library. Specifically, we first show how we can discover requirements on types in order to devise generic algorithms. Then, we focus on how to make algorithms independent of containers through the pivotal abstraction of iterators. To this end, we replicate the standard algorithm for finding the minimum in a sequence (min_element), which we subsequently match with a custom forward iterator over intrusive linked lists of integers. Finally, we see how function objects can be used to customize containers and algorithms alike. This allows us to deepen our understanding of ordering relations, and, in particular, to introduce the concept of strict weak orderings.
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
we are innovative,we are different,we are genius so they call us idiots
Visit us for movies,videos,documentaries,sports,funny pics and many more join www.globalidiots.com
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
we are innovative,we are different,we are genius so they call us idiots
Visit us for movies,videos,documentaries,sports,funny pics and many more join www.globalidiots.com
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
Improving The Quality of Existing SoftwareSteven Smith
Presented at DevReach 2013.
As developers, most of our time is spent working on existing software. Sure, occasionally we get the chance to fire up a new Solution in Visual Studio, and that can be exciting. But after the first day, we find ourselves once more having to deal with the work we did yesterday. And today, we know more than we did yesterday, so there are things we’d do differently, if we had it to do over.
Over time, software rots. If we’re not diligent, our beautiful code can degrade into a worthless mess. Keeping our code in working condition is no different than changing the oil in our car – it’s preventive maintenance. In this session, Steve will look at some common places to look for signs of degradation in existing applications, and steps to take to improve the code. Examples will use C# and primarily ASP.NET.
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...Complement Verb
C++11 is being deployed and the shape of C++14 is becoming clear. This talk examines the foundations of C++. What is essential? What sets C++ apart from other languages? How do new and old features support (or distract from) design and programming relying on this essence?
I focus on the abstraction mechanisms (as opposed to the mapping to the machine): Classes and templates. Fundamentally, if you understand vector, you understand C++.
Type safety and resource safety are key design aims for a program. These aims must be met without limiting the range of applications and without imposing significant run-time or space overheads. I address issues of resource management (garbage collection is not an ideal answer and pointers should not be used as resource handles), generic programming (we must make it simpler and safer), compile-time computation (how and when?), and type safety (casts belongs in the lowest-level hardware interface). I will touch upon move semantics, exceptions, concepts, type aliases, and more. My aim is not so much to present novel features and technique, but to explore how C++’s feature set supports a new and more effective design and programming style.
C++ stl design overview talk at C++ users meetup Ho Chi Minh City. May 2016. Includes an overview of iterators, data structures and algorithms and how they are meant to be used together.
The presentation discusses software design. It discusses the characteristics of a good and bad design. Then it talks about how to achieve a good design. Then finally we discuss the SOLID Principles of Object Oriented Design. These are 5 principles compiled by Rober Cecil Martin aka Uncle Bob. The benefit of these principles is to achieve a good OO design which is high in cohesion and low in coupling thus easily adaptable to change
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Interface Segregation Principle and the Dependency Inversion Principle. This session will explain them thoroughly and give real life examples instead of the regular customer & order examples. You'll walk away knowing what the benefits are and how to use them properly.
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Single Responsibility Principle and the Open/Closed Principle, two of the presenter's favorite principles. But at the same time the least understood and used principles. That's why this session will explain them thoroughly and give real life examples instead of the regular customer & order examples. You'll walk away knowing what the benefits are and how to use them properly.
Gentle Introduction to Functional ProgrammingSaurabh Singh
This slide is basically aimed at professionals and students to introduce them with functional programming.
I haven't used much functional programming terminologies because I personally feel they could be overwhelming to people getting introduced to FP for the first time. For similar reasons I have deliberately avoided using any functional programming language and kept the discussions programming language agnostic as far as possible.
lab08/build.bat
@echo off
cls
set DRIVE_LETTER=%1:
set PATH=%DRIVE_LETTER%\MinGW\bin;%DRIVE_LETTER%\MinGW\msys\1.0\bin;%DRIVE_LETTER%\MinGW\gtkmm3\bin;%DRIVE_LETTER%\MinGW\gtk\bin;c:\Windows;c:\Windows\system32
set PROJECT_PATH=.
make DRIVE_LETTER="%DRIVE_LETTER%" PROJECT_DIR="%PROJECT_PATH%"
lab08/CSC2110/CD.h
#if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC2110::String;
#include "ListArray.h"
using CSC2110::ListArray;
namespace CSC2110
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
lab08/CSC2110/Double.h
#if !defined (DOUBLE_H)
#define DOUBLE_H
namespace CSC2110
{
class Double
{
private:
double value;
public:
Double(double val);
~Double();
double getValue();
};
}
#endif
lab08/CSC2110/HighPerformanceCounter.h
#if !defined (HIGHPERFORMANCECOUNTER_H)
#define HIGHPERFORMANCECOUNTER_H
namespace CSC2110
{
class HighPerformanceCounter
{
private:
double micro_spt; //micro_seconds per tick
HighPerformanceCounter();
static HighPerformanceCounter* hpc;
static int getTicksPerSecond();
public:
virtual ~HighPerformanceCounter();
static HighPerformanceCounter* getHighPerformanceCounter();
int getCurrentTimeInTicks();
double getTimeDifferenceInMicroSeconds(int start_time, int end_time);
};
}
#endif
lab08/CSC2110/Integer.h
#if !defined (INTEGER_H)
#define INTEGER_H
namespace CSC2110
{
class Integer
{
private:
int value;
public:
Integer(int val);
virtual ~Integer();
int getValue();
};
}
#endif
lab08/CSC2110/Keyboard.h
#if !defined KEYBOARD_H
#define KEYBOARD_H
#include "Text.h"
using CSC2110::String;
#include <string>
using namespace std;
namespace CSC2110
{
class Keyboard
{
private:
Keyboard();
public:
virtual ~Keyboard();
static Keyboard* getKeyboard();
//pre: the string (character literal) that will prompt the user for input
//post: the input read from the keyboard interpreted as an int is returned
int readInt(string prompt);
int getValidatedInt(string prompt, int min, int max);
//pre: the string that will prompt the user for input
//post: the input read from the keyboard interpreted as a double is returned
double readDouble(string prompt);
double getValidatedDouble(string prom ...
1sequences and sampling. Suppose we went to sample the x-axis from X.pdfrushabhshah600
1sequences and sampling. Suppose we went to sample the x-axis from Xmin to Xmax using a
step size of step
A)Draw a picture of what is going on.
B) Write a expression for n the total number of samples involved (in terms of Xmin, Xmax and
step)
C) Write out the sequence of x-samples
D) Write a direct and general expression for xi that captures the sequence
E) Write a recursive expression for the sequence
F) Write a program to compute and store the x-samples over the range -5x5 using a step size of
0.1 do everything in main ()
2 . We talked about the following string functions that are available in C (as long as you include
string.h):
int strlen(char str[])
void strcpy(char str1[], char str2[])
void strcat(char str1[], str2[])
Write your own versions of these functions; for example: int paul_strlen(int char str[]). Hint: for
your version of the strlen function, start at the first character in the array and keep counting until
you find the ‘\\0’ character (use a while loop for this). Note: Use your version of the strlen
function in the strcpy and strcat functions.
9. We want to insert a number into an array.
(a) Formulate the problem mathematically with two sequences: x and y. (b) Write a function of
the form:
insertNumIntoArray(int n, int array[], int num, int index)
The function inserts num into the array at the specified index. The rest of the array then follows.
For example, if num = 9 and index = 3 and array = [7 2 8 8 3 1 2] then the function will produce:
array = [7 2 8 9 8 3 1 2]
Note: assume that array is properly dimensioned to have at least 1 extra space for storage.
10. Repeat #2 by for the delete operation; that is, we want to delete a single element (at a
specified index) from an array; for example, suppose index = 3 and array = [50 70 10 90 60 20],
then the result will be
array: [50 70 10 60 20]
11. Repeat #2 by for an insert operation where we are inserting several values into the array. The
function should be of the form:
int insertArrayIntoArray(int n, int inArray[],
int nInsert, int insertArray[], int outArray[], int index)
The dimension of outArray is returned (explicitly). For example:
inArrayarray: [7 2 8 6 3 9]
insertArray: [50 60 70]
index: 2
outArray: [7 2 50 60 70 8 6 3 9]
Assume that outArray is large enough to hold all n + nInsert values.
Solution
#include
//Simulates strlen() library function
int paul_strlen(char str[])
{
int l;
for(l = 0; str[l] != \'\\0\'; l++) ;
return l;
}
//Simulates strcpy() library function
void paul_strcpy(char str1[], char str2[])
{
int c;
for(c = 0; str1[c] != \'\\0\'; c++)
str2[c] = str1[c];
str2[c] = \'\\0\';
printf(\"\ Original String: %s\", str1);
printf(\"\ Copied String: %s\", str2);
}
//Simulates strcat() library function
void paul_strcat(char str1[], char str2[])
{
int i, j;
for(i = 0; str1[i] != \'\\0\'; i++) ;
for (j = 0; str2[j] != \'\\0\'; i++, j++)
{
str1[i] = str2[j];
}
str1[i] = \'\\0\';
printf(\"\ Concatenated String: %s\", str1);
}
int main()
{
char data1[20], data2[20];
pri.
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
4. Pointer
Point to an address in memory.
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer = NULL;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
5. Const?? Pointer??
Able to change p && *p:
int* p;
Able to change p, but not *p
int* const p;
Able to change *p, but not p
const int* p;
Unable to change p || *p
const int* const p;
6. Array && operator[]
The name of an array is a pointer to the first
element of the array.
arr[index] equals to *(arr+index)
arr[0] equals to *arr
const int arr[] = {1, 2, 3, 4};
cout << arr[0] << endl
<< *arr << endl;
They are equal.
7. Reference
Similar to pointer, but not changeable.
int a = 0, b = 1;
int &ref = a;
ref = 2;
Using in function parameter:
#include <iostream>
using namespace std;
int sum(int (&a)[4])
{
return a[0]+a[1]+a[2]+a[3];
}
int main()
{
int arr[4] = {1, 2, 3, 4};
cout << sum(arr);
}
8. Dynamic Memory
pointer = new type;
pointer = new type [number_of_elements];
delete pointer;
delete [] pointer;
int *pa = new int;
int *parr = new int[10];
*pa = 1, parr[0] = 1;
delete pa;
delete [] pa;
9. Templates
template<typename T>
inline const T& max(const T& a, const T& b)
{
return a > b ? a : b;
}
template<typename T1, typename T2>
struct pair
{
T1 first;
T2 second;
};
template<typename T, size_t N>
class array
{
T _data[N];
};
13. Part of STL Algorithm
Notices:
#include <algorithm>
using namespace std;
* Know it
$ Useful
! Extremely useful && important
14. * std::equal - O(n)
template <class InputIterator1, class InputIterator2>
bool equal ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2 );
Compares the elements in the range
[first1,last1) with those in the range
beginning at first2, and returns true if the
elements in both ranges are considered equal.
int myints[] = {20,40,60,80,100};
int myints2[] = {20,40,60,80,100};
if (equal (mynts, myints+5, myints2))
cout << "The contents of both sequences are equal." << endl;
else
cout << "The contents of both sequences differ." << endl;
15. * std::fill - O(n)
template < class ForwardIterator, class T >
void fill ( ForwardIterator first, ForwardIterator last, const T& value );
Sets value to all elements in the range
[first,last).
vector<int> myvector (8); // myvector:00000000
fill (myvector.begin(),myvector.begin()+4,5);// myvector:55550000
fill (myvector.begin()+3,myvector.end()-2,8);// myvector:55588800
16. * std::find - O(n)
template <class InputIterator, class T>
InputIterator find ( InputIterator first, InputIterator last, const T&
value );
Returns an iterator to the first element in
the range [first,last) that compares equal to
value, or last if not found.
int myints[] = { 10, 20, 30 ,40 };
int * p = find(myints,myints+4,30);
++p;
cout << "The element following 30 is " << *p << endl;
17. $ std::lower_bound /
std::upper_bound - O(logn)
template <class ForwardIterator, class T>
ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator
last, const T& value );
Returns an iterator pointing to the first
element in the sorted range [first,last) which
does not compare less than value.
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
vector<int>::iterator low,up;
sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
low=lower_bound (v.begin(), v.end(), 20); // ^
up= upper_bound (v.begin(), v.end(), 20); // ^
cout << "lower_bound at position " << int(low- v.begin()) << endl;
cout << "upper_bound at position " << int(up - v.begin()) << endl;
18. $ std::make_heap - O(n)
template <class RandomAccessIterator>
void make_heap ( RandomAccessIterator first,
RandomAccessIterator last );
Rearranges the elements in the range
[first,last) in such a way that they form a
heap.
#include <funcional>
int myints[] = {10,20,30,5,15};
make_heap (myints,myints+5);
cout << "initial max heap : " << myints[0] << endl;
make_heap (myints,myints+5,greater<int>());
cout << "initial min heap : " << myints[0] << endl;
20. $ std::sort_heap - O(nlogn)
template <class RandomAccessIterator>
void sort_heap ( RandomAccessIterator first, RandomAccessIterator last );
Rearranges the elements in the heap range
[first,last) in such a way that they form a
sorted range.
The range loses its heap properties.
int myints[] = {10,20,30,5,15};
make_heap (myints,myints+5)
cout << "initial max heap : " << v.front() << endl;
sort_heap (myints,myints+5;
cout << "final sorted range :";
for (unsigned i=0; i<5; i++) cout << " " << myints[i];
21. $ std::max_element /
std::min_element - O(n)
template <class ForwardIterator>
ForwardIterator max_element ( ForwardIterator first, ForwardIterator
last );
Returns an iterator pointing to the
element with the largest value in the
range [first,last).
int myints[] = {3,7,2,5,6,4,9};
cout << "The smallest element is " << *min_element(myints,myints+7) <<
endl;
cout << "The largest element is " << *max_element(myints,myints+7) << endl;
22. $ std::nth_element - On average O(n)
template <class RandomAccessIterator>
void nth_element ( RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last );
Rearranges the elements in the range
[first,last), in such a way that the element at
the resulting nth position is the element that
would be in that position in a sorted sequence,
with none of the elements preceding it being
greater and none of the elements following it
smaller than it.
Neither the elements preceding it nor the
elements following it are guaranteed to be
ordered.
23. ! std::swap - O(1)
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}
24. ! std::max / std::min - O(1)
template <class T> const T& max ( const T& a, const T& b ) {
return (a<b)?b:a;
}
26. ! std::sort - O(nlogn)
Sort by two keys:
#include <iostream>
#include <algorithm>
struct Point
{
int x, y;
Point(const int _x = 0, const int _y = 0): x(_x), y(_y) { }
};
inline bool operator<(const Point& lhs, const Point& rhs)
{ return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y); }
27. ! std::sort - O(nlogn)
Point a[100];
int n;
int main()
{
std::cin >> n;
for (int i = 0; i < n; ++i)
std::cin >> a[i].x >> a[i].y;
std::sort(a, a+n);
std::cout << std::endl;
for (int i = 0; i < n; ++i)
std::cout << a[i].x << ' ' << a[i].y << std::endl;
std::cout << std::endl << (a[1] < a[2])
<< std::endl << (a[2] < a[1]);
}
28. ! std::unique - O(n)
template <class ForwardIterator>
ForwardIterator unique ( ForwardIterator first, ForwardIterator last );
Removes the duplicate consecutive elements
from the range [first,last). This is done by
removing from the resulting range all the
elements that compare equal to the element
right preceding them (only the first element in
each group of consecutive equal elements is
kept).
The resulting range consists of the elements
between first and the iterator returned by the
function, which points to the new end of range.
The elements past the new end of range are
still valid, although with unspecified values.
int myints[] = {10,20,20,20,30,30,20,20,10};
sort(myints, myints+9);
int n = unique(myints, myints+9) - myints;
29. A Part of STL Container
! vector
! deque
list
! stack
! queue
priority_queue
! set
multiset
! map
multimap
! bitset
30. vector deque set map bitset
begin O(1) v v v v
end O(1) v v v v
rbegin O(1) v v v v
rend O(1) v v v v
size * O(1) O(1) O(1) O(1) O(1)
empty O(1) v v v v v
front O(1) v v v
back O(1) v v v
operator[] * O(1) O(1) O(logn) O(logn) O(1)
at O(1) v v
assign O(n) v v
insert * O(n) O(n) O(logn) O(logn)
erase * O(n) O(n) O(logn) O(logn)
clear O(n) v v v v
push_front O(1) v v
pop_front O(1) v v
push_back O(1) v v v
pop_back O(1) v v v
find O(logn) v v
count O(logn) v v v
31. Initializing Container Elements
C<T> c; Create an empty container named c . C is a container
name, such as vector , and T is the element type.
C c(c2); Create c as a copy of container c2 ; c and c2 must be
the same container type and hold values of the same
type.
C c(b, e); Create c with a copy of the elements from the range
denoted by iterators b and e .
C c(n, t); Create c with n elements, each with value t , which
must be a value of the element type of C or a type
convertible to that type.
Sequential containers only.
C c(n); Create c with n value-initialized
Sequential containers only.
33. Iterator Ranges && Container-
Defined Iterator Typedefs
[ first, last )
while (first != last) {
// safe to use *first because we know there is at least one element
++first;
}
iterator Type of the iterator for this container
type
const_iterator Type of the iterator that can read but
not write the elements
reverse_iterator Iterator that addresses elements in
reverse order
const_reverse_iterator Reverse iterator that can read but not
write the elements
34. begin and end Members
c.begin() Yields an iterator referring to the first element in
c
c.end() Yields an iterator referring to the one past the
last element in c
c.rbegin() Yields a reverse iterator referring to the last
element in c
c.rend() Yields a reverse iterator referring one past (i.e.,
before) the first element in c
for (vector<int>::reverse_iterator beg = c.rbegin(); beg != c.rend();
++beg)
{
}
35. Operations that Add Elements
to a Sequential Container
c.push_back(t) Adds element with value t to the end of c .
Returns void .
c.push_front(t) Adds element with value t to front of c . Returns
void .
Valid only for list or deque .
c.insert(p,t) Inserts element with value t before the element
referred to by iterator p . Returns an iterator
referring to the element that was added.
c.insert(p,n,t) Inserts n elements with value t before the
element referred to by iterator p . Returns void .
c.insert(p,b,e) Inserts elements in the range denoted by
iterators b and e before the element referred to
by iterator p . Returns void .
36. Size Operations && Access Elements
c.size() Returns the number of elements in c . Return type
is c::size_type .
c.empty() Returns a bool that indicates whether size is 0 or
not.
c.back() Returns a reference to the last element in c .
Undefined if c is empty.
c.front() Returns a reference to the first element in c .
Undefined if c is empty.
c[n] Returns a reference to the element indexed by n .
Undefined if n <0 or n >= c.size() .
Valid only for vector and deque .
c.at(n) Returns a reference to the element indexed by n .
If index is out of range, throws out_of_range
exception.
Valid only for vector and deque .
37. Operations to Remove Elements
c.erase(p) Removes element referred to by the iterator p .
Returns an iterator referring to the element after
the one deleted, or an off-the-end iterator if p
referred to the last element. Undefined if p is an
off-the-end iterator.
c.erase(b,e) Removes the range of elements denoted by the
iterators b and e . Returns an iterator referring
after the last one in the range that was deleted,
or an off-the-end iterator if e is itself an off-
the-end iterator.
c.clear() Removes all the elements in c . Returns void .
c.pop_back() Removes the last element in c . Returns void .
Undefined if c is empty.
c.pop_front() Removes the first element in c . Returns void .
Undefined if c is empty.
Valid only for list or deque .
38. stack
stack<T> s;
bool empty ( ) const;
void pop ( );
void push ( const T& x );
size_type size ( ) const;
value_type& top ( );
const value_type& top ( ) const;
39. queue
queue<T> q;
value_type& back ( );
const value_type& back ( ) const;
bool empty ( ) const;
value_type& front ( );
const value_type& front ( ) const;
void pop ( );
void push ( const T& x );
size_type size ( ) const;
40. deque
deque<T> d;
reference at ( size_type n );
const_reference at ( size_type n ) const;
reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;
bool empty ( ) const;
reference front ( );
const_reference front ( ) const;
void pop_back ( );
void pop_front ( );
void push_back ( const T& x );
void push_front ( const T& x );
41. priority_queue
priority_queue<T> p;
priority_queue<T, vector<T>, greater<T> > p;
value_type& back ( );
const value_type& back ( ) const;
bool empty ( ) const;
value_type& front ( );
const value_type& front ( ) const;
void pop ( );
void push ( const T& x );
size_type size ( ) const;
42. vector
vector<T> v;
reference back ( );
const_reference back ( ) const;
reference front ( );
const_reference front ( ) const;
reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;
void pop_back ( );
void push_back ( const T& x );
size_type size() const;
44. map
map<Key, T> m;
map<string, int> m;
bool empty ( ) const;
void erase ( iterator position ); // O(1)
size_type erase ( const key_type& x ); // O(logn)
iterator find ( const key_type& x );
const_iterator find ( const key_type& x ) const;
pair<iterator,bool> insert ( const value_type& x );
T& operator[] ( const key_type& x );
If x does not match the key of any element in the
container, the function inserts a new element with
that key and returns a reference to its mapped value.
45. set
set<T> s;
size_type count ( const key_type& x ) const;
bool empty ( ) const;
void erase ( iterator position ); // O(1)
size_type erase ( const key_type& x ); // O(logn)
iterator find ( const key_type& x ) const;
pair<iterator,bool> insert ( const value_type& x );
48. USACO - majesty
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%d%d", &a[i].x, &a[i].y);
std::sort(a, a+n);
n = std::unique(a, a+n) - a;
unsigned int area(sqr(a[0].y-a[0].x));
for (int i = 1; i < n; ++i)
{
area += sqr(a[i].y-a[i].x);
if (a[i].x < a[i-1].y)
area -= sqr(a[i-1].y-a[i].x);
}
printf("%d", area);
}