This document discusses containers like vectors and lists in C++. It provides examples of declaring and initializing vectors with different data types. Functions are demonstrated for printing, inserting, and searching elements in a vector. The document also contains examples of declaring and iterating through lists, and functions for inserting and removing elements from a list.
This macro finds the last row of data on two worksheets, copies data from one range to another on a different worksheet, removes any duplicate values, and selects the target range. It activates different worksheets, finds the last row, copies and pastes values from one range to another, and removes duplicate values in the target range.
The document discusses arrays in C++ and compares them to vectors. It notes that arrays allocate memory from the heap using new, return a pointer, and have less features than vectors. Indexing an array uses pointer arithmetic behind the scenes. The document warns that memory allocated for arrays is uninitialized unlike variables with automatic storage, and demonstrates issues that can occur when using uninitialized or out-of-bounds array elements.
The new and delete operators in C++ are used for dynamic memory allocation and deallocation. New allocates memory at runtime and returns a pointer to the allocated block. Delete frees up memory that was previously allocated by new. The general syntax for new is pointer = new datatype and for delete is delete pointer. Dynamic memory allocation allows programs to be more flexible by allocating memory as needed at runtime rather than statically.
This Java code uses nested while loops to print a descending triangular grid of numbers. It takes user input, initializes a variable x to 10, then uses the outer while loop to decrement x down to 1, printing each row. The inner while loop prints each number in the row, decrementing the variable y by 2 until it reaches the value of x minus 6, then it prints a new line before continuing the outer loop.
Arrays in C allow storing multiple values of the same data type in a single variable. An array is declared with the data type, array name, and size. Elements in an array are accessed using indexes that run from 0 to size-1. Multidimensional arrays can also be declared to store arrays of arrays.
Collections in .net technology (2160711)Janki Shah
Collections in .NET Framework.
- What is collections?
- Needs of Collections/ importance of collection
- various most useful classes of collection such as
ArrayList, Hashtable, Stack, Queue, BitArray, SortedList
This document discusses arrays in three sentences:
Arrays are collections of homogeneous data that can be one-dimensional, two-dimensional, or multi-dimensional. One-dimensional arrays store data in a single subscript, while two-dimensional arrays arrange data into rows and columns. Array elements are accessed via an index and each dimension of a multi-dimensional array is identified by a subscript.
- The document outlines the agenda for today's class which includes announcements, projects due, and an upcoming quiz. The class will cover sections 3.1 and 3.2 on functions.
- It defines what a function is and provides examples. A function assigns each input to exactly one output. It discusses function notation and evaluating functions.
- Additional topics covered include finding domains of functions, piecewise functions, graphing functions using a T-chart, reading graphs, and determining if a relation represents a function using the vertical line test. Worksheets are assigned for classwork and homework.
This macro finds the last row of data on two worksheets, copies data from one range to another on a different worksheet, removes any duplicate values, and selects the target range. It activates different worksheets, finds the last row, copies and pastes values from one range to another, and removes duplicate values in the target range.
The document discusses arrays in C++ and compares them to vectors. It notes that arrays allocate memory from the heap using new, return a pointer, and have less features than vectors. Indexing an array uses pointer arithmetic behind the scenes. The document warns that memory allocated for arrays is uninitialized unlike variables with automatic storage, and demonstrates issues that can occur when using uninitialized or out-of-bounds array elements.
The new and delete operators in C++ are used for dynamic memory allocation and deallocation. New allocates memory at runtime and returns a pointer to the allocated block. Delete frees up memory that was previously allocated by new. The general syntax for new is pointer = new datatype and for delete is delete pointer. Dynamic memory allocation allows programs to be more flexible by allocating memory as needed at runtime rather than statically.
This Java code uses nested while loops to print a descending triangular grid of numbers. It takes user input, initializes a variable x to 10, then uses the outer while loop to decrement x down to 1, printing each row. The inner while loop prints each number in the row, decrementing the variable y by 2 until it reaches the value of x minus 6, then it prints a new line before continuing the outer loop.
Arrays in C allow storing multiple values of the same data type in a single variable. An array is declared with the data type, array name, and size. Elements in an array are accessed using indexes that run from 0 to size-1. Multidimensional arrays can also be declared to store arrays of arrays.
Collections in .net technology (2160711)Janki Shah
Collections in .NET Framework.
- What is collections?
- Needs of Collections/ importance of collection
- various most useful classes of collection such as
ArrayList, Hashtable, Stack, Queue, BitArray, SortedList
This document discusses arrays in three sentences:
Arrays are collections of homogeneous data that can be one-dimensional, two-dimensional, or multi-dimensional. One-dimensional arrays store data in a single subscript, while two-dimensional arrays arrange data into rows and columns. Array elements are accessed via an index and each dimension of a multi-dimensional array is identified by a subscript.
- The document outlines the agenda for today's class which includes announcements, projects due, and an upcoming quiz. The class will cover sections 3.1 and 3.2 on functions.
- It defines what a function is and provides examples. A function assigns each input to exactly one output. It discusses function notation and evaluating functions.
- Additional topics covered include finding domains of functions, piecewise functions, graphing functions using a T-chart, reading graphs, and determining if a relation represents a function using the vertical line test. Worksheets are assigned for classwork and homework.
The document provides examples of using various C++ standard library containers and algorithms. It shows how to define a phone book using map and unordered_map containers and retrieve phone numbers by name. It also lists different container types and their characteristics, and provides examples of algorithms like sort, find, copy, and equal_range.
This document discusses abstract data types and containers in C++. It defines an abstract Container class with pure virtual functions for accessing elements and size. It then shows two classes, Vector_container and List_container, that implement the Container interface to allow a function to generically use different container types.
The document describes C++ templates and how they can be used to define generic containers like Vector that work for different element types. It shows how to define a Vector class with a template parameter T for the element type. It also demonstrates how templates can be used to write algorithms that work on different container types by extracting the element type. Functions, classes, and type aliases can all be templated.
This document provides an overview of arrays, pointers, and strings in C++. It discusses that arrays allow the storage of multiple values of the same data type. Arrays must be declared with a size before use. Elements within an array are accessed via an index with numbering starting at 0. Multidimensional or 2D arrays can store multiple sets of data organized into rows and columns accessed by two indices. Strings are internally stored as character arrays but can be treated as single entities. The document also introduces pointers as variables that store the memory addresses of other variables, and the address operator returns the memory address of its operand.
Arrry structure Stacks in data structurelodhran-hayat
There are two types of arrays in C++: single dimensional and multidimensional arrays. The document then provides examples of using single dimensional arrays, traversing arrays using for loops and foreach loops, using structs with constructors and methods, pointers including declaring, assigning, and dereferencing pointers, and dynamic memory allocation using new and delete operators for built-in types, arrays, objects, and multidimensional arrays.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
Vector is a container that improves on C++ arrays by allowing elements to be added and removed dynamically without specifying a size. Vectors can hold different data types like integers, strings, and custom objects. Elements can be accessed and modified using operator[], and iterated over using begin() and end() iterators. Common operations include push_back() to add elements, pop_back() to remove the last element, and insert() and erase() to modify the elements within the vector. Vectors can be compared using ==, !=, and < to check for equality and sort order.
The document describes the objectives of a C++ lab course. It includes:
1. Designing classes with static members, methods with default arguments, and friend functions like a matrix and vector class.
2. Implementing a complex number class with operator overloading.
3. Implementing a matrix class with dynamic memory allocation.
4. Overloading new and delete operators for custom memory allocation.
5. Developing linked list and sorting algorithm templates.
An array is a collection of similar elements that are stored in contiguous memory locations. Arrays in C can have one or more dimensions. One-dimensional arrays are declared with the type of elements, name of the array, and number of elements within brackets (e.g. int marks[30]). Multi-dimensional arrays represent matrices and are declared with the number of rows and columns (e.g. int arr[5][10]). Individual elements within an array are accessed via indices (e.g. arr[2][7]). Pointers in C are related to arrays - the name of an array represents the address of its first element, and pointer arithmetic can be used to access successive elements in an array.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
The document discusses copy and move semantics in C++. It provides examples of copy initialization, copy assignment, and copy constructors that make copies of objects. It then introduces move semantics using move constructors and move assignment that allow efficiently transferring resources from one object to another. The document shows how to implement move operations for a Vector class and demonstrates their use. It also shows how to delete copy and move operations to prevent objects from being copied or moved.
,,,,,,jhbhhhhhvggvvcccccccfghhhhhhhhhhhhhgggggggggyyyyy hhbbhhhhgggyhhsyddhdhhddhsiejdhajshdhdhdhdhdhdudufjdhyeyeg hhdhdhdhdhdhdhdhdh d bhsuhabuesjjsoeijshshdhsjajsijehfdhhdhdhdhdhhdxbbxxhxhhdja hi in najajajhwhr7fhhhhhhhhhhhhhhhhhuhhuwbshdhhddh8rhedi8fnf
The document introduces several C++ standard library utilities including:
1) Chrono for measuring elapsed time between events in milliseconds.
2) Numeric limits for querying properties of fundamental types like the smallest positive float.
3) Iterator tags and overloading algorithms like sort based on iterator categories.
4) Type traits like is_arithmetic to check properties of types.
5) Pair and tuple for grouping multiple objects of different types.
The document discusses parallel programming concepts in C++ including threads, synchronization using mutexes, condition variables for producer-consumer problems, and futures/promises for asynchronous function calls. It provides examples of spawning threads to execute functions concurrently, protecting shared data with mutexes, notifying condition variables to signal events, and getting values from futures after asynchronous tasks have completed.
This document introduces C++ strings and I/O streams. It shows how to compose an email address from a name and domain, append to strings, extract substrings, and modify strings. Functions are defined to output integers and strings to stdout. The document also demonstrates reading user input, including integers and strings, from stdin. Finally, it defines a struct with name and number fields, overloads insertion and extraction operators for the struct, and uses these operators to read and write structs to I/O streams.
The document introduces the C++ standard library and its main components. It discusses key elements like strings, I/O streams, containers and algorithms. It also mentions how the standard library provides runtime language support, the C standard library, and utilities to support common programming tasks like string handling, I/O, containers, algorithms, numerical computations, concurrency, metaprogramming and smart pointers.
This document discusses C++ data types including fundamental types like int and double, user-defined types like structures and classes, and enumerations. It provides examples of defining a struct called Vector to represent an array, using Vector in a function, and converting Vector to a class. It also shows an example of an enumerator called Color and how to implement operator overloading for a prefix increment operator on an enum.
The document discusses arrays, pointers, references in C++. It defines arrays as collections of elements that can be accessed using indices starting from 0. It shows examples of declaring and initializing arrays, looping through arrays, copying arrays, printing array elements, and incrementing array elements. It also defines pointers as variables that store the address of another variable. It discusses pointer arithmetic and pointer to functions. It defines references as aliases to existing variables that must be initialized.
The document provides examples of using various C++ standard library containers and algorithms. It shows how to define a phone book using map and unordered_map containers and retrieve phone numbers by name. It also lists different container types and their characteristics, and provides examples of algorithms like sort, find, copy, and equal_range.
This document discusses abstract data types and containers in C++. It defines an abstract Container class with pure virtual functions for accessing elements and size. It then shows two classes, Vector_container and List_container, that implement the Container interface to allow a function to generically use different container types.
The document describes C++ templates and how they can be used to define generic containers like Vector that work for different element types. It shows how to define a Vector class with a template parameter T for the element type. It also demonstrates how templates can be used to write algorithms that work on different container types by extracting the element type. Functions, classes, and type aliases can all be templated.
This document provides an overview of arrays, pointers, and strings in C++. It discusses that arrays allow the storage of multiple values of the same data type. Arrays must be declared with a size before use. Elements within an array are accessed via an index with numbering starting at 0. Multidimensional or 2D arrays can store multiple sets of data organized into rows and columns accessed by two indices. Strings are internally stored as character arrays but can be treated as single entities. The document also introduces pointers as variables that store the memory addresses of other variables, and the address operator returns the memory address of its operand.
Arrry structure Stacks in data structurelodhran-hayat
There are two types of arrays in C++: single dimensional and multidimensional arrays. The document then provides examples of using single dimensional arrays, traversing arrays using for loops and foreach loops, using structs with constructors and methods, pointers including declaring, assigning, and dereferencing pointers, and dynamic memory allocation using new and delete operators for built-in types, arrays, objects, and multidimensional arrays.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
Vector is a container that improves on C++ arrays by allowing elements to be added and removed dynamically without specifying a size. Vectors can hold different data types like integers, strings, and custom objects. Elements can be accessed and modified using operator[], and iterated over using begin() and end() iterators. Common operations include push_back() to add elements, pop_back() to remove the last element, and insert() and erase() to modify the elements within the vector. Vectors can be compared using ==, !=, and < to check for equality and sort order.
The document describes the objectives of a C++ lab course. It includes:
1. Designing classes with static members, methods with default arguments, and friend functions like a matrix and vector class.
2. Implementing a complex number class with operator overloading.
3. Implementing a matrix class with dynamic memory allocation.
4. Overloading new and delete operators for custom memory allocation.
5. Developing linked list and sorting algorithm templates.
An array is a collection of similar elements that are stored in contiguous memory locations. Arrays in C can have one or more dimensions. One-dimensional arrays are declared with the type of elements, name of the array, and number of elements within brackets (e.g. int marks[30]). Multi-dimensional arrays represent matrices and are declared with the number of rows and columns (e.g. int arr[5][10]). Individual elements within an array are accessed via indices (e.g. arr[2][7]). Pointers in C are related to arrays - the name of an array represents the address of its first element, and pointer arithmetic can be used to access successive elements in an array.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
The document discusses copy and move semantics in C++. It provides examples of copy initialization, copy assignment, and copy constructors that make copies of objects. It then introduces move semantics using move constructors and move assignment that allow efficiently transferring resources from one object to another. The document shows how to implement move operations for a Vector class and demonstrates their use. It also shows how to delete copy and move operations to prevent objects from being copied or moved.
,,,,,,jhbhhhhhvggvvcccccccfghhhhhhhhhhhhhgggggggggyyyyy hhbbhhhhgggyhhsyddhdhhddhsiejdhajshdhdhdhdhdhdudufjdhyeyeg hhdhdhdhdhdhdhdhdh d bhsuhabuesjjsoeijshshdhsjajsijehfdhhdhdhdhdhhdxbbxxhxhhdja hi in najajajhwhr7fhhhhhhhhhhhhhhhhhuhhuwbshdhhddh8rhedi8fnf
The document introduces several C++ standard library utilities including:
1) Chrono for measuring elapsed time between events in milliseconds.
2) Numeric limits for querying properties of fundamental types like the smallest positive float.
3) Iterator tags and overloading algorithms like sort based on iterator categories.
4) Type traits like is_arithmetic to check properties of types.
5) Pair and tuple for grouping multiple objects of different types.
The document discusses parallel programming concepts in C++ including threads, synchronization using mutexes, condition variables for producer-consumer problems, and futures/promises for asynchronous function calls. It provides examples of spawning threads to execute functions concurrently, protecting shared data with mutexes, notifying condition variables to signal events, and getting values from futures after asynchronous tasks have completed.
This document introduces C++ strings and I/O streams. It shows how to compose an email address from a name and domain, append to strings, extract substrings, and modify strings. Functions are defined to output integers and strings to stdout. The document also demonstrates reading user input, including integers and strings, from stdin. Finally, it defines a struct with name and number fields, overloads insertion and extraction operators for the struct, and uses these operators to read and write structs to I/O streams.
The document introduces the C++ standard library and its main components. It discusses key elements like strings, I/O streams, containers and algorithms. It also mentions how the standard library provides runtime language support, the C standard library, and utilities to support common programming tasks like string handling, I/O, containers, algorithms, numerical computations, concurrency, metaprogramming and smart pointers.
This document discusses C++ data types including fundamental types like int and double, user-defined types like structures and classes, and enumerations. It provides examples of defining a struct called Vector to represent an array, using Vector in a function, and converting Vector to a class. It also shows an example of an enumerator called Color and how to implement operator overloading for a prefix increment operator on an enum.
The document discusses arrays, pointers, references in C++. It defines arrays as collections of elements that can be accessed using indices starting from 0. It shows examples of declaring and initializing arrays, looping through arrays, copying arrays, printing array elements, and incrementing array elements. It also defines pointers as variables that store the address of another variable. It discusses pointer arithmetic and pointer to functions. It defines references as aliases to existing variables that must be initialized.
The document discusses different conditional and looping structures in C++ including if/else statements, switch statements, while loops, do-while loops, and for loops. It provides examples of a function called accept that uses these structures to prompt the user for input and return true if they enter 'y' or false otherwise, allowing for multiple tries.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
WWDC 2024 Keynote Review: For CocoaCoders AustinPatrick Weigel
Overview of WWDC 2024 Keynote Address.
Covers: Apple Intelligence, iOS18, macOS Sequoia, iPadOS, watchOS, visionOS, and Apple TV+.
Understandable dialogue on Apple TV+
On-device app controlling AI.
Access to ChatGPT with a guest appearance by Chief Data Thief Sam Altman!
App Locking! iPhone Mirroring! And a Calculator!!
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
How Can Hiring A Mobile App Development Company Help Your Business Grow?ToXSL Technologies
ToXSL Technologies is an award-winning Mobile App Development Company in Dubai that helps businesses reshape their digital possibilities with custom app services. As a top app development company in Dubai, we offer highly engaging iOS & Android app solutions. https://rb.gy/necdnt
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
7. vector<T>
When you insert a new element, it’s value is
copied into the container
8. 01. void silly(vector<Entry>& book)
02. {
03. // book.size() is out of range
04. int i = book[ph.size()].number;
05. // ...
06. }
01. template<typename T>
02. class Vec : public std::vector<T> {
03. public:
04. // use the constructors from vector (under the name Vec)
05. using vector<T>::vector;
06. T& operator[](int i) // range check
07. { return vector<T>::at(i); }
08. const T& operator[](int i) const // range check const objects
09. { return vector<T>::at(i); }
10. }
9. 01. list<Entry> phone_book = {
02. {"David Hume",123456},
03. {"Karl Popper",234567},
04. {"Bertrand Arthur William Russell",345678}
05. };
01. int get_number(const string& s)
02. {
03. for (const auto& x : phone_book)
04. if (x.name==s)
05. return x.number;
06. return 0; // use 0 to represent "number not found"
07. }
10. 01. int get_number(const string& s)
02. {
03. for (auto p = phone_book.begin(); p!=phone_book.end(); ++p)
04. if (p–>name==s)
05. return p–>number;
06. return 0; // use 0 to represent "number not found"
07. }
11. 01. int get_number(const string& s)
02. {
03. for (auto p = phone_book.begin(); p!=phone_book.end(); ++p)
04. if (p–>name==s)
05. return p–>number;
06. return 0; // use 0 to represent "number not found"
07. }
01. void f(const Entry& ee, list<Entry>::iterator p
02. , list<Entry>::iterator q)
03. {
04. // add ee before the element referred to by p
05. phone_book.insert(p, ee);
06. // remove the element referred to by q
07. phone_book.erase(q);
08. }
Editor's Notes
توی این دوباره یه اشاره ای به مفهوم container می کنم و ویدیو وکتور و لیست رو که دوتا از پر کاربرد ترین containerهای کتابخونه استاندارد رو معرفی میکنم.
برنامه هایی که می نویسیم معمولا شامل یه مجموعه از مقادیری مشن که ما اونا رو ایجاد می کنیم و یه collection از اونا رو درست می کنیم و بعد روی اونا عملیاتهایی رو انجام می دیم. مثال کار کردن با string و خوندن کاراکتر ها از روی ورودی و چاپ کردن مقدار اون یه مثال ساده هست.
در ویدیوی شماره 7 در مورد مفهوم containerها صحبت کرده بودیم. هر کلاسی که یه مجموعه از Objectها رو نگه داری کنه بهش می گیم Container. برای اینکه یه کاری رو انجام بدیم باید container مناسب اون کار رو به همراه عملیاتهای پایه ای روی Container رو باید داشته باشیم.
برای اینکه روشن تر بشه فرض کنید که ما می خوایم یه دفترچه تلفن درست کنیم که شامل یه سری نام و شماره تلفن اون نام هست. ما باید طوری این برنامه رو بنویسیم که واضح و خوانا باشه و هر کسی با هر پیش زمینه ای بتونه از اون سر در بیاره. Structی Entry که در ویدیوی قبلی دیدیم می تونه برای نگه داری یه رکورد توی دفترچه تلفن استفاده بشه. توی اون struct خیلی از پیچیدگی های دنیای واقعی رو در نظر نمی گیریم مثلا تلفن های واقعی توی int جا نمی شن ولی برای سادگی ما شماره تلفن رو int در نظر گرفتیم. مثال دفترچه تلفن توی تمام این فصل برای توضیح دادن containerها استفاده می شه.
مفیدترین container در کتابخونه استاندارد وکتوره. وکتور یه sequence از المانهاست که پشت سر هم و به صورت پیوسته در حافظه قرار گرفتند. در مورد وکتور تا حالا خیلی بحث کردیم و مثال زدیم.
ما میتونیم وکتور را با یه set از eleman typeهایی که داره initialize کنیم . توی این مثال یه وکتور از entryها به نام phone_book ساختیم و با 3 تا عنصر مقدار دهی کردیم.
با اپراتور subscript به عناصر اون دسترسی داشته باشیم. Indexها از صفر شروع میشن یعنی book[0] برابر رکورد david hume خواهد بود.
وکتور یه تابع به نام size داره که تعداد المانهای داخل اون رو بر میگردونه. ما از size توی for برای شرط خروج حلقه استفاده کردیم.
ما می تونیم از range for برای دسترسی به المانهای وکتور استفاده کنیم. با range for به تک تک عناصر وکتور دسترسی داریم و می تونیم عملیات انجام بدیم. با استفاده از auto می تونیم type المانهای وکتور رو ننویسیم و کامپایلر خودش به صورت هوشمند این کار رو می کنه.
هر وقت یه وکتور تعریف می کنیم size اون بر اساس المانهایی که برای initializeکردن بهش می دیم مقدار می گیره.
اینجا چون 4 تا المان به عنوان initializer list به وکتور دادیم پس سایز اولیه اون برابر 4 میشه.
اما اینجا وکتور initialize نشده پس مقدار size برابر صفر خواهد شد.
این خط با استفاده از کانستراکتور تک ورودی یه وکتور با 23 تا المان میسازه که مقادیر اولیه اون المانها با nullptr مقدار دهی می شن. اگر برای المانهای وکتور مقدار اولیه تعیین نشه default constructor اون المانها اجرا خواهد شد.
و اینجا با کانستراکتور 2 ورودی 32 تا المان میسازه که با 9.9 مقدار اولیه داده میشن. مقدار اولیه default رو با دادن پارامتر دوم به وکتور میشه تغییر دار و بجای اینکه default constructor اجرا بشه با این پارامتر مقدار دهی میشه.
یکی از فیچر های مهم وکتور اینه که بر خلاف آرایه که سایزش غیرقابل تغییره ، تعداد عناصر داخل vector رو میشه تغییر داد. با تابع push_back میشه یه المان رو به انتهای وکتور اضافه کرد.
تابع input از ورودی یه تعداد entry میخونه و بعد اونارو به انتهای وکتور اضافه میکنه. زمانی این حلقه تموم میشه که به انتهای ورودی برسیم و یا فرمت بندی ورودی اشتباه باشه. Vector طوری پیاده سازی شده که با push_back کردن المانهای جدید، رشد میکنه و بزرگ میشه تا جا برای المانهای جدید هم باز بشه. این بزرگ شدن وکتور رو طوری پیاده سازی کردند که تا حد قابل قبولی efficient باشه.
یه وکتور جدید رو میشه با assignment , initialize کرد. چون copy و move constructor برای وکتور تعریف شده و میشه با Move و Copy کردن وکتور رو initialize کرد. ولی زمانی که وکتور تعداد زیادی المان داخلش باشه copy هزینه ی زیادی داره و باید از move کمک گرفت یا اینکه از pointer یا reference استفاده کرد.
توی این اسلاید در مورد چند تا نکته مهم در مورد المانهای وکتور اشاره میکنم.
وکتور و همه ی containerها کتابخونه استاندارد به صورت templateیی پیاده سازی شده و type المان های اون پارامتری تعیین میشه. پارامتر T میتونه هر چیزی مثل built-in typeها یا Pointerیا user-defined type ها باشه.
وقتی یه المان جدید به وکتور push_back میشه value اون copyمیشه. برای المان های کوچیک مثل اعداد صحیح این کپی کردن هزینه ای نداره ولی اگه اندازه المان ها بزرگتر بشه هزینه ی کپی کردن بالا میره. این نکته ایه که وقتی از وکتور استفاده میکنید باید مد نظر داشته باشید.
یه نکته هم در مورد اپراتور subscript توی این اسلاید میگم و اون اینکه وکتور هیچ تضمینی برای چک کردن دسترسی های out of range یا خارج از محدوده نداره.
برای اینکه این مشکل حل بشه میتونیم یه کلاس به این صورت بنویسم که از وکتور مشتق شده باشه و اپراتور های subscript اون رو باز نویسی کنیم. تابع at یه تابعی هست که برای پیاده سازی subscript استفاده شده. این تابع بر خلاف اپراتور subscript اگر خارج از محدوده بخوایم ازش استفاده کنیم exception از نوع Out_of_range میده. برای اینکه این exception رو catch کنید باید از try catch استفاده کنید که توی ویدیوی شماره 6 با هم دیده بودیم.
بعد از وکتور، توی این اسلاید لیست رو بررسی می کنیم. کتابخونه استاندارد لیست دوطرفه هم برای ما فراهم کرده. از لیست برای نگهداری یه sequence از المان هاست. توی لیست insert و delete کردن المانها اون بدون جابجا کردن بقیه المانها توی حافظه امکان پذیره. برای initialize کردن مثل vector از initializer list استفاده می کنیم.
اما بر خلاف وکتور برای دسترسی به المانها نمی تونیم از subscript استفاده کنیم و باید کل لیست رو برای پیدا کردن المانی که مورد نظرمون هست search کنیم. برای search کردن باید از اولین المان داخل لیست شروع کنیم و تا زمانی که المان رو پیدا نکردیم یا به انتهای لیست نرسیدیم ادامه میدیم. برای پیمایش مثل همه ی containerها می تونیم از range for استفاده کنیم.
ما میتونیم بجای استفاده کردن از range for که در مثال قبل دیدیم از iterator برای پیمایش لیست استفاده کنیم. می تونیم تابع get_nubmer مثال قبل رو به این صورت بازنویسی کنیم.
با استفاده از begin یه interator به ابتدای لیست می گیریم
و با استفاده از end چک می کنیم که به انتهای لیست رسیدیم یا نه
اگر به انتها نرسیدیم؛ مقدار iterator رو یکی اضافه میکنیم. با ++ کردن یه iterator به المان بعدی در اون container اشاره خواهد کرد.
نحوه ی پیاده سازی iterator به صورتی هست که با اون مثل یه pointer باید رفتار کرد. یعنی با اپراتور فلش میشه به اعضای اون المان دسترسی داشت و یا به dereference کردن iterator به خود اون المان دسترسی داشت.
با استفاده از Iterator ها میشه کار های بیشتری انجام داد.
در اینجا با استفاده از متد insert میتونیم یه عنصر رو به لیست اضافه کنیم. با داشتن یه iterator میتونیم یه entry رو قبل از اون iterator در لیست قرار بدیم.
و با داشتن Iterator می تونیم اون المان رو با استفاده از متد erase از لیست حذف کنیم.
اما تفاوت لیست و وکتور چیه. تفاوت اونا توی پیاده سازی اوناست. وکتور های کوچیک با تعداد المانهای کم بهتر از لیست عمل می کنن ولی وقتی تعداد المان ها زیاد میشه و تعداد insert و delete ها زیاد میشه، لیست خیلی بهتر از وکتوره. زمانی که شما به یه sequence از المان ها نیاز دارید باید بین وکتور و لیست یکی رو انتخاب کنید. Performance وکتور برای یه سری از عملیات های پیمایشی مثل findو countو عملیاتهای جستجو و مرتب سازی مثل sort و binary_serach بهتره ولی در لیست هزینه درج و حذف المانها کمتره. این نکات رو در استفاده از این 2 تا container باید در نظر داشته باشید.
در انتها یه جمع بندی بکنیم.
این ویدیو در مورد 2 تا از پر کاربردترین containerها کتابخونه استاندارد یعنی وکتور و لیست صحبت کردیم و امکانات اونا رو بررسی کردیم. و نکاتی که در مورد استفاده از اونا باید در نظر گرفت رو هم گفتیم.