The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
The document discusses arrays and functions in C programming. It defines arrays as collections of similar data items stored under a common name. It describes one-dimensional and two-dimensional arrays, and how they are declared and initialized. It also discusses strings as arrays of characters. The document then defines functions as sets of instructions to perform tasks. It differentiates between user-defined and built-in functions, and describes the elements of functions including declaration, definition, and calling.
Underscore.js is a JavaScript utility library that provides support for functional programming without extending built-in JavaScript objects. It includes over 60 functions for working with arrays, objects, functions and more. Some key functions include map, reduce, find, and bind for working with collections and functions. Underscore is open source and part of the DocumentCloud project.
The document discusses generics in .NET and how they provide type safety and code reuse. It explains that generics allow defining methods and classes that can work with different data types. This is done by specifying type parameters that act as placeholders for the actual types. Some key generic concepts covered include generic methods, classes, interfaces, and common collection classes like List, Stack, Queue and how they allow storing and manipulating different types of data.
This document provides an introduction and overview of arrays in C++. It defines what an array is, how to declare and initialize arrays, and how to access, insert, search, sort, and merge array elements. Key points covered include:
- An array is a sequenced collection of elements of the same data type. Elements are referenced using a subscript index.
- Arrays can be declared with a fixed or variable length. Elements are initialized sequentially in memory.
- Common array operations like accessing, inserting, searching, sorting and merging are demonstrated using for loops and examples. Searching techniques include sequential and binary search. Sorting techniques include selection, bubble and insertion sort.
- Arrays are passed
The objective of the Level 5 Diploma in Information Technology is to provide learners with an excellent foundation for a career in a range of organisations. It designed to ensure that each learner is ‘business ready’: a confident, independent thinker with a detailed knowledge of Information Technology, and equipped with the skills to adapt rapidly to change.
This document discusses generics and collections in .NET. It introduces generics as a way to write reusable code for different data types. Generic methods and classes are covered, allowing a single definition to work with multiple types. The document also discusses collection classes like ArrayList, HashTable, Stack and Queue, which provide common data structures. It notes the benefits of generic collections over non-generic ones in terms of type safety and efficiency.
The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
The document discusses arrays and functions in C programming. It defines arrays as collections of similar data items stored under a common name. It describes one-dimensional and two-dimensional arrays, and how they are declared and initialized. It also discusses strings as arrays of characters. The document then defines functions as sets of instructions to perform tasks. It differentiates between user-defined and built-in functions, and describes the elements of functions including declaration, definition, and calling.
Underscore.js is a JavaScript utility library that provides support for functional programming without extending built-in JavaScript objects. It includes over 60 functions for working with arrays, objects, functions and more. Some key functions include map, reduce, find, and bind for working with collections and functions. Underscore is open source and part of the DocumentCloud project.
The document discusses generics in .NET and how they provide type safety and code reuse. It explains that generics allow defining methods and classes that can work with different data types. This is done by specifying type parameters that act as placeholders for the actual types. Some key generic concepts covered include generic methods, classes, interfaces, and common collection classes like List, Stack, Queue and how they allow storing and manipulating different types of data.
This document provides an introduction and overview of arrays in C++. It defines what an array is, how to declare and initialize arrays, and how to access, insert, search, sort, and merge array elements. Key points covered include:
- An array is a sequenced collection of elements of the same data type. Elements are referenced using a subscript index.
- Arrays can be declared with a fixed or variable length. Elements are initialized sequentially in memory.
- Common array operations like accessing, inserting, searching, sorting and merging are demonstrated using for loops and examples. Searching techniques include sequential and binary search. Sorting techniques include selection, bubble and insertion sort.
- Arrays are passed
The objective of the Level 5 Diploma in Information Technology is to provide learners with an excellent foundation for a career in a range of organisations. It designed to ensure that each learner is ‘business ready’: a confident, independent thinker with a detailed knowledge of Information Technology, and equipped with the skills to adapt rapidly to change.
This document discusses generics and collections in .NET. It introduces generics as a way to write reusable code for different data types. Generic methods and classes are covered, allowing a single definition to work with multiple types. The document also discusses collection classes like ArrayList, HashTable, Stack and Queue, which provide common data structures. It notes the benefits of generic collections over non-generic ones in terms of type safety and efficiency.
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
The document discusses reallocating memory using the realloc() function in C. It provides code to allocate memory for an integer array, print the memory addresses, reallocate the array to a larger size, and print the new memory addresses. The memory addresses for the previously allocated blocks do not change after reallocating, but new contiguous blocks are added to increase the array size.
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
C++ STL is a collection of containers and algorithms that provide common programming tasks. It includes data structures like vector, set, map as well as sorting and searching algorithms. Using STL containers makes code shorter, faster and more error-free compared to manually writing these routines. STL is important for learning advanced C++ concepts like graphs and algorithms.
Intro to C# - part 2.pptx emerging technologyworldchannel
Arrays allow storing a collection of elements of the same type. Arrays can be one-dimensional or multi-dimensional. Functions provide reusable blocks of code that can be called from different parts of a program. Functions can accept parameters by value, reference, or output and can return values. Parameters can also be passed as arrays.
The document outlines an advanced Python course covering various Python concepts like object orientation, comprehensions, extended arguments, closures, decorators, generators, context managers, classmethods, inheritance, encapsulation, operator overloading, and Python packages. The course agenda includes how everything in Python is an object, comprehension syntax, *args and **kwargs, closures and decorators, generators and iterators, context managers, staticmethods and classmethods, inheritance and encapsulation, operator overloading, and Python package layout.
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
Need done for Date Structures please!
4.18 LAB: Sorted number list implementation with linked lists
Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables:
a double data value,
a pointer to the next node, and
a pointer to the previous node.
Each member variable is protected. So code outside of the class must use the provided getter and
setter member functions to get or set a member variable.
Node.h is read only, since no changes are required.
Step 2: Implement the Insert() member function
A class for a sorted, doubly-linked list is declared in SortedNumberList.h. Implement the
SortedNumberList class's Insert() member function. The function must create a new node with
the parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node
with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the Remove() member function
Implement the SortedNumberList class's Remove() member function. The function takes a
parameter for the number to be removed from the list. If the number does not exist in the list, the
list is not changed and false is returned. Otherwise, the first instance of the number is removed
from the list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
#include "SortedNumberList.h"
using namespace std;
void PrintList(SortedNumberList& list);
vector<string> SpaceSplit(string source);
int main(int argc, char *argv[]) {
// Read the line of input numbers
string inputLine;
getline(cin, inputLine);
// Split on space character
vector<string> terms = SpaceSplit(inputLine);
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list;
for (auto term : terms) {
double number = stod(term);
cout << "List after inserting " << number << ": " << endl;
list.Insert(number);
PrintList(list);
}
/*
// Read the input line with numbers to remove
getline(cin, inputLine);
terms = SpaceSplit(inputLine);
// Remove each value
for (auto term : terms) {
double number = stod(term);
cout << "List after removing " << number << ": " << endl;
list.Remove(number.
Enumerable provides a large set of useful methods for enumerations or collections of values. It is a core module that allows objects to be iterated over. Enumerable provides aliases for some methods and optimized versions for common use cases like invoking the same method on each element or fetching the same property from each element. To use Enumerable, an object just needs to provide an _each method that iterates over its elements.
The Java Collections framework provides a unified approach to store, retrieve, and manipulate groups of data. It includes interfaces and classes to implement commonly used data structures like lists, sets, maps, queues, and more. The framework is generic, provides standard algorithms and operations, and improves performance and quality of Java applications. It also supports thread safety through utility methods.
The document provides an introduction to the Standard Template Library (STL) in C++. It describes the main components of STL including containers, iterators, algorithms and function objects. It explains that containers store data, iterators access data, algorithms manipulate data, and function objects can be used by algorithms. Specific containers like vector, deque, list, set and map are outlined along with their characteristics and sample functions. Iterators and their categories are also summarized. Common algorithms like for_each, find, sort and merge are demonstrated through examples. Finally, it shows how function objects can be used by algorithms to customize operations.
This presentation explains few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with the code snippet.
The document summarizes the key components of the Standard Template Library (STL) including containers, iterators, and algorithms. It describes common STL containers like vector, list, set, map and their uses. Iterators are used to point to container elements and algorithms perform operations on container elements. Examples are provided to demonstrate how to use STL containers like vector, set and map as well as common algorithms like sort.
The document provides an overview of common topics that confuse new C programmers, including control structures, variable types, pointers, arrays, structs, linked lists, and recursion. It discusses each concept in 1-3 paragraphs, explaining what they are and providing basic examples. It also covers debugging strategies such as printing variables, reducing complexity, and inserting early returns to isolate issues.
STL stands for Standard Template Library. It provides common programming data structures and algorithms. The key components of STL are containers like vector and list that store data, iterators that access elements in containers, and algorithms that perform operations on data structures. STL aims to provide generic functions that work on different data types through templates. Common STL algorithms include searching, sorting, copying, and erasing elements from containers.
The document discusses arrays in C++. It defines an array as a group of consecutive memory locations with the same name and type. Arrays allow storing multiple values using a single name. The document covers one-dimensional and two-dimensional arrays, including how to declare, initialize, access elements, and write programs to input and output array values. It provides examples of programs that input values into arrays, find the maximum/minimum values, and store/display 2D arrays.
The document discusses time and space complexity analysis for algorithms, including using Big O notation to describe an algorithm's efficiency. It provides examples of time complexity for different codes, such as O(n) for a simple loop and O(n^2) for a double loop. The document also covers space complexity and how to estimate the complexity of a problem based on input size constraints.
This document discusses different types of arrays in C#, including simple arrays, multidimensional arrays, jagged arrays, and tuples. Simple arrays store elements of the same type and can be initialized with syntax like "datatype[] myArray = new datatype[size]". Multidimensional arrays are indexed by two or more integers. Jagged arrays allow each row to have a different size. Tuples were introduced in .NET 4.0 and act as a way to group multiple data types together.
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
C++ code, please help! RESPOND W/ COMPLETED CODE PLEASE, am using Visual Studio
Code.
Error message:
ld: Undefined symbols:
parseName(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::init(), referenced from:
_main in module-a187a7.o
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::insert(std::__1::basic_string, std::__1::allocator>, int), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SubExpression::parse(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
_main in module-a187a7.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Done] exited with code=1 in 1.478 seconds
divide.h
class Divide : public SubExpression
{
public:
//define the default construtor
Divide(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//divide the value of left and value of the right
//and return the value.
return left->evaluate() / right->evaluate();
}
};
expression.h
// Expression
class Expression
{
public:
//declare a virtual function evaluate()
virtual int evaluate() = 0;
};
literal.h
//Operand
class Literal : public Operand
{
public:
//define the construtor
Literal(int value)
{
this->value = value;
}
//define the function evaluate()
//returns the value
int evaluate()
{
return value;
}
private:
int value;
};
minus.h
//define the class Minus subclass of the SubExpression
class Minus : public SubExpression
{
public:
//define the default construtor
Minus(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//subtract the value of right from the value of the left
//and return the value.
return left->evaluate() - right->evaluate();
}
};
module.cpp
#include
#include
#include
#include
#include
using namespace std;
#include "expression.h"
#include "subexpression.h"
#include "symboltable.h"
#include "parse.h"
//create an object of SymbolTable
SymbolTable symbolTable;
//prototype of the function
void parseAssignments(stringstream& in);
//define main function
int main()
{
// declare the variables
Expression* expression;
char paren, comma;
string line;
// create an input file stream
ifstream fin("input.txt");
// check, if the file is not opened
//then display a error message
if (!fin.is_open())
perror("error while opening file");
//use a loop, to read the content from the file
while (getline(fin, line))
{
symbolTable.init();
if (!fin)
break;
stringstream in(line, ios_base::in);
in >> paren;
cout << line << " ";
expression = SubExpression::parse(in);
in >> comma;
//call the function
parseAssignments(in);
//Display the result
int result = expression->evaluate();
cout << "Value = " << result << endl;
}
system("pause");
return 0;
}
//definition of the function p.
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
Pointer is a variable in C++ that holds the address of another variable. Pointers allow accessing the memory location of other variables. There are different types of pointers based on the data type they are pointing to such as integer, character, class etc. Pointers are declared using an asterisk * before the pointer variable name. The address of a variable can be assigned to a pointer using the & address of operator. Pointers can be used to access members of a class and pass arrays to functions. The this pointer represents the address of the object inside member functions. Virtual functions allow dynamic binding at runtime in inheritance.
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
data structures using C 2 sem BCA univeristy of mysoreambikavenkatesh2
The document discusses reallocating memory using the realloc() function in C. It provides code to allocate memory for an integer array, print the memory addresses, reallocate the array to a larger size, and print the new memory addresses. The memory addresses for the previously allocated blocks do not change after reallocating, but new contiguous blocks are added to increase the array size.
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
C++ STL is a collection of containers and algorithms that provide common programming tasks. It includes data structures like vector, set, map as well as sorting and searching algorithms. Using STL containers makes code shorter, faster and more error-free compared to manually writing these routines. STL is important for learning advanced C++ concepts like graphs and algorithms.
Intro to C# - part 2.pptx emerging technologyworldchannel
Arrays allow storing a collection of elements of the same type. Arrays can be one-dimensional or multi-dimensional. Functions provide reusable blocks of code that can be called from different parts of a program. Functions can accept parameters by value, reference, or output and can return values. Parameters can also be passed as arrays.
The document outlines an advanced Python course covering various Python concepts like object orientation, comprehensions, extended arguments, closures, decorators, generators, context managers, classmethods, inheritance, encapsulation, operator overloading, and Python packages. The course agenda includes how everything in Python is an object, comprehension syntax, *args and **kwargs, closures and decorators, generators and iterators, context managers, staticmethods and classmethods, inheritance and encapsulation, operator overloading, and Python package layout.
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
Need done for Date Structures please!
4.18 LAB: Sorted number list implementation with linked lists
Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables:
a double data value,
a pointer to the next node, and
a pointer to the previous node.
Each member variable is protected. So code outside of the class must use the provided getter and
setter member functions to get or set a member variable.
Node.h is read only, since no changes are required.
Step 2: Implement the Insert() member function
A class for a sorted, doubly-linked list is declared in SortedNumberList.h. Implement the
SortedNumberList class's Insert() member function. The function must create a new node with
the parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node
with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the Remove() member function
Implement the SortedNumberList class's Remove() member function. The function takes a
parameter for the number to be removed from the list. If the number does not exist in the list, the
list is not changed and false is returned. Otherwise, the first instance of the number is removed
from the list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
#include "SortedNumberList.h"
using namespace std;
void PrintList(SortedNumberList& list);
vector<string> SpaceSplit(string source);
int main(int argc, char *argv[]) {
// Read the line of input numbers
string inputLine;
getline(cin, inputLine);
// Split on space character
vector<string> terms = SpaceSplit(inputLine);
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list;
for (auto term : terms) {
double number = stod(term);
cout << "List after inserting " << number << ": " << endl;
list.Insert(number);
PrintList(list);
}
/*
// Read the input line with numbers to remove
getline(cin, inputLine);
terms = SpaceSplit(inputLine);
// Remove each value
for (auto term : terms) {
double number = stod(term);
cout << "List after removing " << number << ": " << endl;
list.Remove(number.
Enumerable provides a large set of useful methods for enumerations or collections of values. It is a core module that allows objects to be iterated over. Enumerable provides aliases for some methods and optimized versions for common use cases like invoking the same method on each element or fetching the same property from each element. To use Enumerable, an object just needs to provide an _each method that iterates over its elements.
The Java Collections framework provides a unified approach to store, retrieve, and manipulate groups of data. It includes interfaces and classes to implement commonly used data structures like lists, sets, maps, queues, and more. The framework is generic, provides standard algorithms and operations, and improves performance and quality of Java applications. It also supports thread safety through utility methods.
The document provides an introduction to the Standard Template Library (STL) in C++. It describes the main components of STL including containers, iterators, algorithms and function objects. It explains that containers store data, iterators access data, algorithms manipulate data, and function objects can be used by algorithms. Specific containers like vector, deque, list, set and map are outlined along with their characteristics and sample functions. Iterators and their categories are also summarized. Common algorithms like for_each, find, sort and merge are demonstrated through examples. Finally, it shows how function objects can be used by algorithms to customize operations.
This presentation explains few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with the code snippet.
The document summarizes the key components of the Standard Template Library (STL) including containers, iterators, and algorithms. It describes common STL containers like vector, list, set, map and their uses. Iterators are used to point to container elements and algorithms perform operations on container elements. Examples are provided to demonstrate how to use STL containers like vector, set and map as well as common algorithms like sort.
The document provides an overview of common topics that confuse new C programmers, including control structures, variable types, pointers, arrays, structs, linked lists, and recursion. It discusses each concept in 1-3 paragraphs, explaining what they are and providing basic examples. It also covers debugging strategies such as printing variables, reducing complexity, and inserting early returns to isolate issues.
STL stands for Standard Template Library. It provides common programming data structures and algorithms. The key components of STL are containers like vector and list that store data, iterators that access elements in containers, and algorithms that perform operations on data structures. STL aims to provide generic functions that work on different data types through templates. Common STL algorithms include searching, sorting, copying, and erasing elements from containers.
The document discusses arrays in C++. It defines an array as a group of consecutive memory locations with the same name and type. Arrays allow storing multiple values using a single name. The document covers one-dimensional and two-dimensional arrays, including how to declare, initialize, access elements, and write programs to input and output array values. It provides examples of programs that input values into arrays, find the maximum/minimum values, and store/display 2D arrays.
The document discusses time and space complexity analysis for algorithms, including using Big O notation to describe an algorithm's efficiency. It provides examples of time complexity for different codes, such as O(n) for a simple loop and O(n^2) for a double loop. The document also covers space complexity and how to estimate the complexity of a problem based on input size constraints.
This document discusses different types of arrays in C#, including simple arrays, multidimensional arrays, jagged arrays, and tuples. Simple arrays store elements of the same type and can be initialized with syntax like "datatype[] myArray = new datatype[size]". Multidimensional arrays are indexed by two or more integers. Jagged arrays allow each row to have a different size. Tuples were introduced in .NET 4.0 and act as a way to group multiple data types together.
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
C++ code, please help! RESPOND W/ COMPLETED CODE PLEASE, am using Visual Studio
Code.
Error message:
ld: Undefined symbols:
parseName(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::init(), referenced from:
_main in module-a187a7.o
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SymbolTable::insert(std::__1::basic_string, std::__1::allocator>, int), referenced from:
parseAssignments(std::__1::basic_stringstream, std::__1::allocator>&) in module-a187a7.o
SubExpression::parse(std::__1::basic_stringstream, std::__1::allocator>&), referenced from:
_main in module-a187a7.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Done] exited with code=1 in 1.478 seconds
divide.h
class Divide : public SubExpression
{
public:
//define the default construtor
Divide(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//divide the value of left and value of the right
//and return the value.
return left->evaluate() / right->evaluate();
}
};
expression.h
// Expression
class Expression
{
public:
//declare a virtual function evaluate()
virtual int evaluate() = 0;
};
literal.h
//Operand
class Literal : public Operand
{
public:
//define the construtor
Literal(int value)
{
this->value = value;
}
//define the function evaluate()
//returns the value
int evaluate()
{
return value;
}
private:
int value;
};
minus.h
//define the class Minus subclass of the SubExpression
class Minus : public SubExpression
{
public:
//define the default construtor
Minus(Expression* left, Expression* right) : SubExpression(left, right)
{
}
//define the function evaluate()
int evaluate()
{
//subtract the value of right from the value of the left
//and return the value.
return left->evaluate() - right->evaluate();
}
};
module.cpp
#include
#include
#include
#include
#include
using namespace std;
#include "expression.h"
#include "subexpression.h"
#include "symboltable.h"
#include "parse.h"
//create an object of SymbolTable
SymbolTable symbolTable;
//prototype of the function
void parseAssignments(stringstream& in);
//define main function
int main()
{
// declare the variables
Expression* expression;
char paren, comma;
string line;
// create an input file stream
ifstream fin("input.txt");
// check, if the file is not opened
//then display a error message
if (!fin.is_open())
perror("error while opening file");
//use a loop, to read the content from the file
while (getline(fin, line))
{
symbolTable.init();
if (!fin)
break;
stringstream in(line, ios_base::in);
in >> paren;
cout << line << " ";
expression = SubExpression::parse(in);
in >> comma;
//call the function
parseAssignments(in);
//Display the result
int result = expression->evaluate();
cout << "Value = " << result << endl;
}
system("pause");
return 0;
}
//definition of the function p.
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
Pointer is a variable in C++ that holds the address of another variable. Pointers allow accessing the memory location of other variables. There are different types of pointers based on the data type they are pointing to such as integer, character, class etc. Pointers are declared using an asterisk * before the pointer variable name. The address of a variable can be assigned to a pointer using the & address of operator. Pointers can be used to access members of a class and pass arrays to functions. The this pointer represents the address of the object inside member functions. Virtual functions allow dynamic binding at runtime in inheritance.
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
Similar to Object Oriented Programming Using C++: C++ STL Programming.pptx (20)
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMHODECEDSIET
Time Division Multiplexing (TDM) is a method of transmitting multiple signals over a single communication channel by dividing the signal into many segments, each having a very short duration of time. These time slots are then allocated to different data streams, allowing multiple signals to share the same transmission medium efficiently. TDM is widely used in telecommunications and data communication systems.
### How TDM Works
1. **Time Slots Allocation**: The core principle of TDM is to assign distinct time slots to each signal. During each time slot, the respective signal is transmitted, and then the process repeats cyclically. For example, if there are four signals to be transmitted, the TDM cycle will divide time into four slots, each assigned to one signal.
2. **Synchronization**: Synchronization is crucial in TDM systems to ensure that the signals are correctly aligned with their respective time slots. Both the transmitter and receiver must be synchronized to avoid any overlap or loss of data. This synchronization is typically maintained by a clock signal that ensures time slots are accurately aligned.
3. **Frame Structure**: TDM data is organized into frames, where each frame consists of a set of time slots. Each frame is repeated at regular intervals, ensuring continuous transmission of data streams. The frame structure helps in managing the data streams and maintaining the synchronization between the transmitter and receiver.
4. **Multiplexer and Demultiplexer**: At the transmitting end, a multiplexer combines multiple input signals into a single composite signal by assigning each signal to a specific time slot. At the receiving end, a demultiplexer separates the composite signal back into individual signals based on their respective time slots.
### Types of TDM
1. **Synchronous TDM**: In synchronous TDM, time slots are pre-assigned to each signal, regardless of whether the signal has data to transmit or not. This can lead to inefficiencies if some time slots remain empty due to the absence of data.
2. **Asynchronous TDM (or Statistical TDM)**: Asynchronous TDM addresses the inefficiencies of synchronous TDM by allocating time slots dynamically based on the presence of data. Time slots are assigned only when there is data to transmit, which optimizes the use of the communication channel.
### Applications of TDM
- **Telecommunications**: TDM is extensively used in telecommunication systems, such as in T1 and E1 lines, where multiple telephone calls are transmitted over a single line by assigning each call to a specific time slot.
- **Digital Audio and Video Broadcasting**: TDM is used in broadcasting systems to transmit multiple audio or video streams over a single channel, ensuring efficient use of bandwidth.
- **Computer Networks**: TDM is used in network protocols and systems to manage the transmission of data from multiple sources over a single network medium.
### Advantages of TDM
- **Efficient Use of Bandwidth**: TDM all
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSIJNSA Journal
The smart irrigation system represents an innovative approach to optimize water usage in agricultural and landscaping practices. The integration of cutting-edge technologies, including sensors, actuators, and data analysis, empowers this system to provide accurate monitoring and control of irrigation processes by leveraging real-time environmental conditions. The main objective of a smart irrigation system is to optimize water efficiency, minimize expenses, and foster the adoption of sustainable water management methods. This paper conducts a systematic risk assessment by exploring the key components/assets and their functionalities in the smart irrigation system. The crucial role of sensors in gathering data on soil moisture, weather patterns, and plant well-being is emphasized in this system. These sensors enable intelligent decision-making in irrigation scheduling and water distribution, leading to enhanced water efficiency and sustainable water management practices. Actuators enable automated control of irrigation devices, ensuring precise and targeted water delivery to plants. Additionally, the paper addresses the potential threat and vulnerabilities associated with smart irrigation systems. It discusses limitations of the system, such as power constraints and computational capabilities, and calculates the potential security risks. The paper suggests possible risk treatment methods for effective secure system operation. In conclusion, the paper emphasizes the significant benefits of implementing smart irrigation systems, including improved water conservation, increased crop yield, and reduced environmental impact. Additionally, based on the security analysis conducted, the paper recommends the implementation of countermeasures and security approaches to address vulnerabilities and ensure the integrity and reliability of the system. By incorporating these measures, smart irrigation technology can revolutionize water management practices in agriculture, promoting sustainability, resource efficiency, and safeguarding against potential security threats.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
2. What is STL?
STL stands for Standard Template Library.
It's a powerful set of C++ template classes to provide general-purpose classes and
functions with templates.
A crucial part of C++ for data manipulation and algorithm development.
Purpose of STL
Simplify and accelerate software development.
Reusable, generic data structures and algorithms.
Improve code quality and maintainability.
Benefits of Using STL:
Saves development time.
Increases code readability.
Maximizes code reuse.
Enhances code performance.
Introduction to STL
3. Containers
Vector: Dynamic array.
List: Doubly linked list.
Algorithms
Sort: Sorting elements.
Find: Searching elements.
Iterators
Input Iterators: Read-only traversal.
Forward Iterators: Supports both reading and writing values in a forward direction.
Bidirectional Iterators: reading and writing values in forward and backward directions.
Random Access Iterator: Supports reading and writing values in any order.
Functors
Function Objects: Callable objects.
Custom operations using operator overloading.
Components of STL
Map: Key-value pairs.
Set: Unique values collection.
Transform: Modifying elements.
Many more for various operations.
Output Iterators: Write-only traversal.
5. Sequence Containers
Container Characteristic Advantages and Disadvantages
C++ array Fixed size Quick random access (by index number)
Slow to insert or erase in the middle
Size cannot be changed at runtime
vector Relocating,
expandable array
Quick random access (by index number)
Slow to insert or erase in the middle
Quick to insert or erase at end
list Doubly linked list Quick to insert or delete at any location
Quick access to both ends
Slow random access
deque Like vector, but can be
accessed at either end
Quick random access (using index number).
Slow to insert or erase in the middle
Quick insert or erase (push and pop) at either the beginning
or the end
6. Container Adapters
Container Implementation Characteristic
stack Can be implemented
as vector, list, or deque
Insert (push) and remove (pop) at one end only
queue Can be implemented
as list or deque
Insert (push) at one end and remove (pop) at other end
priority_queue Can be implemented
as vector or deque
Insert (push) in random order at one end and remove (pop) in
sorted order from other end
7. Associative Containers
Container Characteristic Advantages and Disadvantages
set Stores only the key objects
Only one key of each value allowed
The set is used to store unique elements.
The data is stored in a particular order
(increasing order, by default).
multiset Stores only the key objects
Multiple key values allowed
Multiset is similar to a set but also
allows duplicate values.
map Associates key object with value object
Only one key of each value allowed
The map contains elements in the form of unique key-
value pairs. Each key can be associated with only
one value. It establishes a one-to-one mapping. The
key-value pairs are inserted in increasing order of the
keys.
multimap Associates key object with value object
Multiple key values allowed
Multimap is similar to a map but allows duplicate key-
value pairs to be inserted. Ordering is again done
based on keys.
8. Some Typical STL Algorithms
Algorithm Purpose
find Returns first element equivalent to a specified value
count Counts the number of elements that have a specified value
equal Compares the contents of two containers and returns true if all corresponding elements are equal
search It commonly used to find a subsequence within a specified range of elements.
copy Copies a sequence of values from one container to another
swap Exchanges a value in one location with a value in another
iter_swap Exchanges a sequence of values in one location with a sequence of values in another location
fill Copies a value into a sequence of locations
sort Sorts the values in a container according to a specified ordering
merge Combines two sorted ranges of elements to make a larger sorted range
accumulate Returns the sum of the elements in a given range
for_each Executes a specified function for each element in the container
9. #include <iostream>
#include <algorithm> //for find()
using namespace std;
int arr[] = { 11, 00, 22, 33, 44, 55, 66, 77 };
int main(){
int* ptr;
ptr = find(arr, arr+8, 33) ; //find first 33
// The 1st parameter is the iterator of (or in this case the pointer to) the
// first value to be examined
// The 2nd parameter is the iterator of (or in this case the pointer to) the
// last value to be examined
if((ptr-arr) < 8)
cout << "First object with value 33 found at offset " << (ptr-arr) << endl;
else
cout << "Not Found" << endl;
return 0;
}
Example 1: Using find() Algorithm
10. #include <iostream>
#include <algorithm> //for count()
using namespace std;
int arr[] = { 33, 22, 33, 44, 33, 55, 66, 77};
int main() {
int n = count(arr, arr+8, 33) ; //count number of 33’s
cout << "There are " << n << " 33's in arr." << endl;
return 0;
}
Example 2: Using count() Algorithm
11. #include <iostream>
#include <algorithm>
using namespace std;
int source[] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 };
int pattern[] = { 11, 22, 33 };
int main(){
int* ptr;
ptr = search(source, source+9, pattern, pattern+3) ;
if(ptr == source+9) //if past-the-end
cout << "No match foundn";
else
cout << "Match Found at Index " << (ptr - source) << endl;
return 0;
}
Example 3: Using search() Algorithm
12. #include <iostream>
#include <algorithm>
using namespace std;
// array of numbers
int arr[] = {45, 2, 22, -17, 0, -30, 25, 55};
int main(){
sort(arr, arr + 8); // sort the numbers
for(int j=0; j<8; j++) // display sorted array
cout << arr[j] <<' ';
cout << endl;
return 0;
}
Example 4: Using sort() Algorithm
13. #include <iostream>
#include <algorithm> // for sort()
#include <functional> // for greater<>
using namespace std;
double fdata[] = { 19.2, 87.4, 33.6, 55.0, 11.5, 42.2 }; // array of doubles
int main(){
sort( fdata, fdata+6, greater<double>() ); // sort the doubles
for(int j=0; j<6; j++) // display sorted doubles
cout << fdata[j] << ' ';
cout << endl;
return 0;
}
Example 5: Using greater<>() Function Object
14. #include <iostream>
#include <string> // for strcmp()
#include <algorithm>
using namespace std;
char* names[] = { "George", "Penny", "Estelle", "Don", "Mike", "Bob" };
bool alpha_comp(char*, char*); // custom function object declaration
int main(){
sort(names, names+6, alpha_comp); // sort the strings
for(int j=0; j<6; j++) // display sorted strings
cout << names[j] << endl;
return 0;
}
bool alpha_comp(char* s1, char* s2){ // returns true if s1<s2
return ( strcmp(s1, s2)<0 ) ? true : false;
}
Example 6: Using Custom Function Object
15. #include <iostream>
#include <algorithm> // for merge()
using namespace std;
int src1[] = { 2, 3, 4, 6, 8 };
int src2[] = { 1, 3, 5 };
int dest[8];
int main(){
// merge src1 and src2 into dest
merge(src1, src1+5, src2, src2+3, dest);
for(int j=0; j<8; j++) // display dest
cout << dest[j] << ' ';
cout << endl;
return 0;
}
Example 7: Using merge() Algorithm
16. Some algorithms have versions that end in _if.
These algorithms take an extra parameter called a predicate, which is a function object or a
function.
For example, the find() algorithm finds all elements equal to a specified value.
We can also create a function that works with the find_if() algorithm to find elements with
any arbitrary characteristic.
Our example uses string objects.
The find_if() algorithm is supplied with a user-written isDon() function to find the first
string in an array of string objects that has the value “Don”.
Our next program implements this concept.
Adding _if to Algorithms
17. #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string names[] = { "George", "Estelle", "Don", "Mike", "Bob" };
bool isDon(string name) { // returns true if name == "Don"
return name == "Don";
}
int main() {
string* ptr;
ptr = find_if( names, names+5, isDon );
if(ptr==names+5)
cout << "Don is not on the list.n";
else
cout << "Don is element " << (ptr-names) << " on the list.n";
return 0;
}
Example 8: Using find_if() Algorithm
18. The for_each() algorithm allows you to do something to every item in a container.
You write your own function to determine what that “something” is.
Your function can’t change the elements in the container, but it can use or display their
values.
Here’s an example in which for_each() is used to convert all the values of an array from
inches to centimeters and display them.
We write a function called in_to_cm() that multiplies a value by 2.54, and use this function’s
address as the third argument to for_each().
Here’s the listing for FOR_EACH:
The for_each() Algorithm
19. #include <iostream>
#include <algorithm>
using namespace std;
void in_to_cm(double); // declaration
int main() {
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; // array of inches values
for_each(inches, inches+5, in_to_cm); // output as centimeters
cout << endl;
return 0;
}
void in_to_cm(double in){ // convert and display as centimeters
cout << (in * 2.54) << ' ';
}
Example 9: Using for_each() Algorithm
20. The transform() algorithm does something to every item in a container, and places the
resulting values in a different container (or the same one).
Again, a user-written function determines what will be done to each item.
The return type of this function must be the same as that of the destination container.
Our example is similar to FOR_EACH, except that instead of displaying the converted values,
our in_to_cm() function puts the centimeter values into a different array, centi[].
The main program then displays the contents of centi[].
The transform() Algorithm
21. #include <iostream>
#include <algorithm>
using namespace std;
int main(){
double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; // array of inches values
double centi[5];
double in_to_cm(double); // prototype
transform(inches, inches+5, centi, in_to_cm); // transform into array centi[]
for(int j=0; j<5; j++) // display array centi[]
cout << centi[j] << ' ';
cout << endl;
return 0;
}
double in_to_cm(double in) { // convert inches to centimeters
return (in * 2.54); // return result
}
Example 10: Using transform() Algorithm
22. You can think of vectors as smart arrays.
They manage storage allocation for you, expanding and contracting the size of the vector as
you insert or erase data.
The insert() and erase() member functions insert or remove an element from an
arbitrary location in a container.
These functions aren’t very efficient with vectors, since all the elements above the
insertion or erasure must be moved to make space for the new element or close up the
space where the erased item was.
However, insertion and erasure may nevertheless be useful if speed is not a factor.
You can use vectors much like arrays, accessing elements with the [] operator.
Such random access is very fast with vectors.
It’s also fast to add (or push) a new data item onto the end (the back) of the vector. When
this happens, the vector’s size is automatically increased to hold the new item.
Vector
23. #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v ; // create a vector of integers
v.push_back(10) ; // use push_back() to put values at end of array
v.push_back(11);
v.push_back(12);
v.push_back(13);
v[0] = 20; // use operator[] to read or write values
v[3] = 23;
for(int j=0; j < v. size(); j++) // display vector contents
cout << v[j] << ' '; // it will show 20 11 12 23 on screen
cout << endl;
return 0;
}
Example 11: Using vector Container
24. #include <iostream>
#include <vector>
using namespace std;
int main(){
double arr[] = { 1.1, 2.2, 3.3, 4.4 }; // an array of doubles
vector<double> v1(arr, arr+4); // initialize vector to array
vector<double> v2(4); // empty vector of size 4
v1.swap(v2); // swap contents of v1 and v2
while( !v2.empty() ){ // until vector is empty,
cout << v2.back() << ' '; // display the last element
v2.pop_back(); // remove the last element
} // output: 4.4 3.3 2.2 1.1
cout << endl;
return 0;
}
Eg 12: Using swap(), empty(), back(), and pop_back()
25. #include <iostream>
#include <vector>
using namespace std;
int main(){
double arr[] = { 1.1, 2.2, 3.3, 4.4 }; // an array of doubles
vector<double> v1(arr, arr+4); // initialize vector to array
vector<double> v2(4); // empty vector of size 4
v1.swap(v2); // swap contents of v1 and v2
while( !v2.empty() ){ // until vector is empty,
cout << v2.back() << ' '; // display the last element
v2.pop_back(); // remove the last element
} // output: 4.4 3.3 2.2 1.1
cout << endl;
return 0;
}
Eg 13: Using swap(), empty(), back(), and pop_back()
26. #include <iostream>
#include <vector>
using namespace std;
int main() {
unsigned int i; int arr[] = {100,110,120,130}; // an array of integers
vector<int> v(arr, arr+4); // initialize vector to array
cout << "Before insertion: ";
for(i=0; i<v.size(); i++) // display all elements
cout << v[i] << ' '; // 100 110 120 130
v.insert( v.begin()+2, 115); // insert 115 at element 2
cout << "nAfter insertion: ";
for(i=0; i<v.size(); i++) // display all elements
cout << v[i] << ' '; // 100 110 115 120 130
v.erase( v.begin()+2 ); // erase element 2
cout << "nAfter erasure: ";
for(i=0; i<v.size(); i++) // display all elements
cout << v[i] << ' '; // 100 110 120 130
cout << endl; return 0; }
Example 14: Using insert() and erase()
27. The insert() member function takes two arguments:
the place where an element will be inserted in a container,
and the value of the element.
We add 2 to the begin() member function to specify element 2 (the third element) in the
vector.
The elements from the insertion point to the end of the container are moved upward to
make room, and the size of the container is increased by 1.
The erase() member function removes the element at the specified location.
The elements above the deletion point are moved downward, and the size of the
container is decreased by 1.
Using insert() and erase()
28. An STL list container is a doubly linked list, in which each element contains a pointer not
only to the next element but also to the preceding one.
The container stores the address of both the front (first) and the back (last) elements,
which makes for fast access to both ends of the list.
Insertion and deletion of elements are fast and efficient compared to some other data
structures, such as vectors or arrays, especially when dealing with elements in the middle of
the list.
Unlike vectors, lists don't require reallocation when elements are added or removed. This
can be advantageous in scenarios where the number of elements changes frequently.
Unlike arrays or vectors, lists do not support constant-time random access to elements.
Accessing elements by index takes linear time because you have to traverse the list from the
beginning or end to reach the desired position.
Doubly-linked lists have a higher memory overhead compared to vectors because each
element in the list requires storage for the data and two pointers (prev and next).
List
29. #include <iostream>
#include <list>
using namespace std;
int main() {
list<int> ilist;
ilist.push_back(30); // push items on back {30}
ilist.push_back(40); // {30, 40}
ilist.push_front(20); // push items on front {20, 30, 40}
ilist.push_front(10); // {10 ,20, 30, 40}
int size = ilist.size(); // number of items = 4
for(int j=0; j<size; j++){
cout << ilist.front() << ' '; // read item from front
ilist.pop_front(); // pop item off front
}
cout << endl;
return 0;
}
Example 15: Using list Container
30. #include <iostream>
#include <list>
using namespace std;
int main(){
int j; list<int> list1, list2;
int arr1[] = { 40, 30, 20, 10 }; int arr2[] = { 15, 20, 25, 30, 35 };
for(j=0; j<4; j++) list1.push_back( arr1[j] ); // list1: 40, 30, 20, 10
for(j=0; j<5; j++) list2.push_back( arr2[j] ); // list2: 15, 20, 25, 30, 35
list1.reverse(); // reverse list1: 10 20 30 40
list1.merge(list2); // merge list2 into list1: 10 15 20 20 25 30 30 35 40
list1.unique(); // remove duplicate 20 and 30 list1: 10 15 20 25 30 35 40
int size = list1.size();
while( !list1.empty() ) {
cout << list1.front() << ' '; // read item from front 10 15 20 25 30 35 40
list1.pop_front(); // pop item off front
}
cout << endl; return 0;
}
Example 16: Using deque(), merge(), and unique()
31. A deque is like a vector in some ways and like a linked list in others. Like a vector, it supports
random access using the [] operator.
However, like a list, a deque can be accessed at the front as well as the back. It’s a sort of
double-ended vector, supporting push_front(), pop_front() and front().
Memory is allocated differently for vectors and queues. A vector always occupies a
contiguous region of memory. If a vector grows too large, it may need to be moved to a new
location where it will fit. A deque, on the other hand, can be stored in several non-
contiguous areas; it is segmented.
A member function, capacity(), returns the largest number of elements a vector can
store without being moved, but capacity() isn’t defined for deques because they don’t need
to be moved.
Deque
32. #include <iostream>
#include <deque>
using namespace std;
int main(){
deque<int> deq;
deq.push_back(30); // push items on back {30}
deq.push_back(40); // {30,40}
deq.push_back(50); // {30,40,50}
deq.push_front(20); // push items on front {20,30,40,50}
deq.push_front(10); // {10,20,30,40,50}
deq[2] = 33; // change middle item {10,20,33,40,50}
for(int j=0; j<deq.size(); j++)
cout << deq[j] << ' '; // display items 10,20,33,40,50
cout << endl;
return 0;
}
Example 17: Using dque
34. Iterators are central to the operation of the STL. The role played by iterators is
As a smart pointer
as a connection between algorithm and container.
Iterators as Smart Pointers
In C++, we use a pointer or the [] operator to access data from an array.
For example, in the following code a pointer ptr iterates through an array and accesses
values of each element.
Here, we dereference the pointer ptr with the * operator to obtain the value of the item it
points to and increment it with the ++ operator so it points to the next item.
Iterators
float* ptr = start_address;
for(int j=0; j<SIZE; j++)
cout << *ptr++;
35. Plain C++ pointers face limitations with more sophisticated containers, particularly when
items are not contiguous in memory.
For non-contiguous structures like linked lists, incrementing a pointer becomes complex as
items are not necessarily adjacent.
Storing a pointer to a container element may lead to issues if the container is modified
(insertions or deletions), affecting the validity of the stored pointer.
Smart pointers provide a solution to these problems by wrapping member functions around
ordinary pointers.
These smart pointers can handle non-contiguous memory or changes in element locations.
Overloading operators like ++ and * allows smart pointers to operate on elements within
their containers, offering a solution to challenges posed by dynamic container
modifications.
Here’s how that might look, in skeleton form:
Iterators as Smart Pointers
36. If an algorithm needs only to step forward through a container, reading (but not writing to)
one item after another, it can use an input iterator to connect itself to the container.
Actually, input iterators are typically used, not with containers, but when reading from files
or cin.
If an algorithm steps through the container in a forward direction but writes to the
container instead of reading from it, it can use an output iterator. Output iterators are
typically used when writing to files or cout.
If an algorithm steps along forward and may either read from or write to a container, it
must use a forward iterator.
If an algorithm must be able to step both forward and back through a container, it must use
a bidirectional iterator.
if an algorithm must access any item in the container instantly, it must use a random access
iterator. Random access iterators are like arrays, in that you can access any element. They
can be manipulated with arithmetic operations, as in iter2 = iter1 + 7;
Iterator categories
37. You can see, all iterators support ++ operator for stepping forward through the container.
The input iterator can use the * operator on the right side of the equal sign (but not on
the left): value = *iter;
The output iterator can use the * operator only on the right: *iter = value;
Capabilities of Different Iterator Categories
38. STL automatically makes a bidirectional iterator for list, because that’s what a list requires.
An iterator to a vector or a deque is automatically created as a random-access iterator.
Iterator Types Accepted by Containers
39. Type of Iterator Required by Algorithms
The replace() algorithm
requires a forward iterator,
but it will work with a
bidirectional or a random
access iterator as well
40. In containers that provide random access iterators (vector and queue) it’s easy to iterate
through the container using the [] operator.
Containers such as lists, which don’t support random access, require a different approach.
A more practical approach is to define an iterator for the container.
The next program shows how that might look:
Data Access using iterators
41. #include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
int arr[] = { 2, 4, 6, 8 };
list<int> theList;
for(int k=0; k<4; k++) // fill list with array elements
theList.push_back( arr[k] );
list<int>::iterator it; // iterator to list-of-ints
for(it = theList.begin(); it != theList.end(); it++)
cout << *it << ' '; // display the list
cout << endl;
return 0;
}
Example 18: Data Access using iterators
42. #include <iostream>
#include <list>
using namespace std;
int main() {
list<int> iList(5); // empty list holds 5 ints
list<int>::iterator it; // iterator
int data = 0;
// fill list with data
for(it = iList.begin(); it != iList.end(); it++)
*it = data += 2;
// display list
for(it = iList.begin(); it != iList.end(); it++)
cout << *it << ' ';
cout << endl; return 0;
}
Example 19: Data Insertion using iterators
* operator works on the
left side of the equal
sign as well as the right
43. #include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main() {
list<int> theList(5); // empty list holds 5 ints
list<int>::iterator it; // iterator
int data = 0;
for(it = theList.begin(); it != theList.end(); it++) // fill list with data
*it = data += 2; // 2, 4, 6, 8, 10
it = find(theList.begin(), theList.end(), 8); // look for number 8
if( it != theList.end() ) cout << "Found 8.n" ;
else cout << "Did not find 8.n";
return 0;
}
Example 20: Using find() Algorithm and Iterator
A list iterator is only a
bidirectional iterator, so you
can’t perform arithmetic with it
44. #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> v(5); // empty vector can hold 5 ints
vector<int>::iterator it; // iterator
int data = 0;
for(it = v.begin(); it != v.end(); it++) // fill vector with data
*it = data += 2; // 2, 4, 6, 8, 10
it = find(v.begin(), v.end(), 8); // look for number 8
if( it != v.end() ) cout << "Found 8 at Index " << (it-v.begin() ) <<endl;
else cout << "Did not find 8.n";
return 0;
}
Example 21: Using find() Algorithm and Iterator
You can do arithmetic with random
access iterators, such as those used
with vectors and queues
45. #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int beginRange, endRange;
int arr[] = { 11, 13, 15, 17, 19, 21, 23, 25, 27, 29 };
vector<int> v1(arr, arr+10); // initialized vector
vector<int> v2(10); // uninitialized vector
cout << "Enter range to be copied (example: 2 5): ";
cin >> beginRange >> endRange;
vector<int>::iterator iter1 = v1.begin() + beginRange;
vector<int>::iterator iter2 = v1.begin() + endRange;
vector<int>::iterator iter3;
Example 22: Using copy() Algorithm and Iterator
46. // copy range from v1 to v2
iter3 = copy( iter1, iter2, v2.begin() ); // (it3 -> last item copied)
iter1 = v2.begin(); //
while(iter1 != iter3)// iterate through range in v2, displaying values
cout << *iter1++ << ' ';
cout << endl;
return 0;
}
Example 22: Using copy() Algorithm and Iterator
47. Suppose you want to iterate backward through a container, from the end to the beginning.
You might think you could say something like
but unfortunately this doesn’t work. (For one thing, the range will be wrong (from n to 1,
instead of from n–1 to 0).
To iterate backward you can use a reverse iterator. The ITEREV program shows an example
where a reverse iterator is used to display the contents of a list in reverse order.
Using Reverse Iterator
list<int>::iterator iter; // normal iterator
iter = iList.end(); // start at end
while( iter != iList.begin() ) //go to beginning
cout << *iter-- << ' '; // decrement iterator
48. Advantages:
Fast Search Time: The elements in a map are stored in a sorted order based on their
keys. This allows for efficient binary search operations, resulting in fast retrieval of
elements.
Automatic Sorting: The map automatically sorts its elements based on the keys. This can
be a significant advantage when the data needs to be maintained in a sorted order
without the need for manual sorting.
Unique Keys: Each key in a map must be unique. This property ensures that there are no
duplicate keys, which can be useful in scenarios where uniqueness is crucial.
Associative Relationships: The map allows you to establish associations between keys
and values. So, it is easy to implement and work with key-value pairs in your program.
Dynamic Size: The size of a map can change dynamically as elements are inserted or
removed. This dynamic nature is useful when the number of elements in the container is
not known in advance.
Common STL Containers: Map
49. Disadvantages:
Memory Overhead: The underlying data structure of a map typically involves the use of
pointers and dynamic memory allocation, which can result in a higher memory overhead
compared to some other containers.
Slower Insertion and Deletion: Inserting or deleting elements in a map involves
maintaining the sorted order of the elements, which can make these operations slower
compared to unordered containers like unordered_map.
Not Cache-Friendly: The memory access patterns of a binary search tree, on which a map
is based, may not be as cache-friendly as some other data structures. This can lead to
slightly slower performance in certain scenarios.
Limited Iteration Performance: While searching for a specific element is efficient,
iterating over all elements in a map may not be as fast as in some other containers,
especially when compared to contiguous memory structures.
Common STL Containers: Map
50. Advantages:
Sorted Order: std::set maintains elements in sorted order, which can be advantageous in
scenarios where you need to iterate through elements in a specific order.
Unique Elements: std::set ensures that all elements are unique. This can simplify certain
algorithms and prevent duplicate entries.
Efficient Lookup: Searching for an element in a set has a time complexity of O(log n),
making it efficient for applications that require quick lookups.
Dynamic Size: std::set dynamically adjusts its size, making it suitable for situations where
the number of elements can change during runtime.
Common STL Containers: Set
51. Disadvantages:
No Duplicate Elements: While the uniqueness of elements can be an advantage, it can
also be a limitation if you need to store multiple occurrences of the same value.
Insertion Overhead: Inserting elements into a std::set can have a higher time complexity
(O(log n)) compared to other containers like std::unordered_set. If frequent insertions
and removals are necessary, an std::unordered_set might be a better choice.
Limited Operations: std::set does not support direct access or modification of individual
elements. You can only insert and remove elements, but not change them directly. If you
need to modify elements, you may need to erase and insert again.
Memory Overhead: std::set may have a higher memory overhead compared to other
containers due to the need to maintain a sorted order. If memory efficiency is crucial,
you might want to consider alternatives.
Iterating Complexity: Although elements are in sorted order, iterating through them has
a time complexity of O(n), where n is the size of the set. If frequent iteration is a primary
concern, other containers like std::vector may be more suitable.
Common STL Containers: Set
52. Advantages:
Efficient for FIFO Operations: Queues are designed to efficiently handle elements in a
first-in, first-out manner.
Easy to Use: It provides a simple and easy-to-use interface, with member functions like
push(), pop(), front(), and empty().
Memory Management: STL queues handle memory management internally, so
developers don't need to worry about memory allocation and deallocation when adding
or removing elements.
Thread Safety: In a multithreaded environment, STL queues (like other containers in STL)
are generally thread-safe, meaning they can be safely used in concurrent programs
without the need for additional synchronization.
Standardized Interface: Being part of the C++ Standard Template Library, queues in STL
provide a standardized interface. This allows for consistency and portability across
different C++ implementations.
Common STL Containers: Queue
53. Disadvantages:
Fixed Size: STL queues have a fixed size once created. If dynamic resizing is required,
developers may need to implement their own logic or choose a different container type.
No Random Access: Unlike some other data structures, queues do not provide random
access to elements. Access is limited to the front and back of the queue, which might be
a limitation in certain scenarios.
Limited Functionality: While queues are excellent for FIFO operations, they may not be
the best choice for scenarios that require operations like sorting or searching. Other data
structures, such as vectors or lists, might be more suitable for such cases.
Overhead: There might be a slight overhead associated with using a queue due to the
additional functionality it provides. For simple scenarios, this overhead may be
unnecessary.
Dependency on STL: If you're working in an environment where STL is not available or
not desired, using STL containers, including queues, might not be an option.
Common STL Containers: Queue
54. Stack
Characteristics:
LIFO (Last-In, First-Out) data structure
Typically implemented using deque or vector.
Use Cases:
When you need to implement a stack or perform operations like depth-first search.
Common STL Containers: Stack
55. What are Iterators?
Iterators are objects that allow you to traverse the elements of a container.
Iterators act as pointers to elements within a container.
Types of Iterators
begin(): Points to the first element.
end(): Points one past the last element.
different containers may have additional types of iterators (e.g., rbegin(), rend() for reverse iteration).
How to Use Iterators
Initialize an iterator using begin().
Iterate through the container elements using a loop.
Terminate the loop when the iterator reaches end().
Code Example: Iterating through a Vector
Next code demonstrates how to use iterators to iterate through a vector
Benefits of Iterators
Advantages of using iterators are abstraction, compatibility with various containers, and ease of use.
STL Iterators
56. #include <iostream>
#include <vector>
int main() {
std::vector<int> v1 = { 1, 2, 3, 4, 5 };
// Using iterators to traverse the vector
for (std::vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Example 1: Using Iterator
Page 1
57. Iterators provide a way to access and manipulate each element of the container
sequentially, allowing you to update, insert, or delete elements as needed.
This approach is often used for tasks like searching and replacing specific elements, filtering
data, or applying transformations to elements within the container without the need for
explicit loops.
It can make code more efficient and concise by abstracting away the iteration logic and
providing a clean way to interact with container elements.
Examples of common modifications:
Inserting elements.
Deleting elements.
Modifying elements.
Using Iterators to Manipulate Containers
58. #include <iostream>
#include <list>
int main() {
std::list<int> myList = { 1, 2, 3, 4, 5 };
// Using iterators to modify elements
std::list<int>::iterator it = myList.begin();
++it; // Move to the second element
// Modify the second element
*it = 42;
// Display the modified list
for (const int& value : myList) {
std::cout << value << " ";
}
return 0;
}
Example 2: Modifying Elements in a List
Page 1
59. Common Algorithms
Sorting algorithms (std::sort)
Searching algorithms (std::find)
Transforming algorithms (std::transform)
And many more...
STL Algorithms
60. Example: Sorting a vector
Syntax: std::sort(begin, end)
In-place sorting
Sorting data using std::sort.
Sorting with std::sort
61. Searching for an element
Syntax: std::find(begin, end, value)
Returns an iterator to the found element or end()
Finding elements in a list.
Searching with std::find
62. Applying a function to elements
Syntax: std::transform(begin1, end1, begin2, operation)
Modifies elements or creates a new container
• Example 6: Applying algorithms for data transformation.
Transforming with std::transform
63. #include <iostream>
#include <vector>
#include <algorithm>
int doubleValue(int x) { return 2 * x; } // Function to double a value
int main() {
std::vector<int> num = { 1, 2, 3, 4, 5 };
// Create a destination vector to store the transformed values
std::vector<int> transformedNumbers(num.size());
// Use std::transform to double each element in the 'numbers' vector and store
// the result in 'transformedNumbers'
std::transform(num.begin(), num.end(), transformedNumbers.begin(), doubleValue);
// Print the original and transformed vectors
std::cout << "Original numbers: ";
for (int num : numbers) { std::cout << num << " "; }
std::cout << "nTransformed numbers: ";
for (int num : transformedNumbers) { std::cout << num << " "; }
std::cout << std::endl; return 0;
}
Example 3: using std::transform
Page 1
65. #include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> numbers = { 1, 2, 3, 4, 5 };
// Use std::accumulate to sum all the elements in the 'numbers' vector
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
// Print the original vector and the accumulated sum
std::cout << "Original numbers: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << "nSum of numbers: " << sum << std::endl;
return 0;
}
Example 4: using std::accumulate
Page 1
66. How to apply algorithms to different container types (e.g., vector, list)
Using iterators to specify the range
Be mindful of container requirements (e.g., random access for sorting)
Algorithm Complexity
Discuss time and space complexity of algorithms
Help choose the right algorithm for specific tasks
Example: O(N log N) for std::sort
Benefits of STL Algorithms
Code reusability and readability
Improved maintainability
Enhanced efficiency through optimized implementations
Applying Algorithms to Container Data