Cours de C++ Utilisations des conteneurs



Similar documents
Why you shouldn't use set (and what you should use instead) Matt Austern

Bevezetés a C++ Standard Template Library-be

Zabin Visram Room CS115 CS126 Searching. Binary Search

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Curriculum Map. Discipline: Computer Science Course: C++

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Sequences in the C++ STL

Linked Lists: Implementation Sequences in the C++ STL

Cpt S 223. School of EECS, WSU

recursion, O(n), linked lists 6/14

Chapter Objectives. Chapter 9. Sequential Search. Search Algorithms. Search Algorithms. Binary Search

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Object Oriented Software Design II

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

DATA STRUCTURES USING C

C++ Support for Abstract Data Types

6. Standard Algorithms

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Symbol Tables. Introduction

Object Oriented Software Design II

LINKED DATA STRUCTURES

Glossary of Object Oriented Terms

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

IMPROVING PERFORMANCE OF RANDOMIZED SIGNATURE SORT USING HASHING AND BITWISE OPERATORS

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

C++ Programming Language

An Incomplete C++ Primer. University of Wyoming MA 5310

7.1 Our Current Model

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

C++ INTERVIEW QUESTIONS

Sample Questions Csci 1112 A. Bellaachia

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Binary Heap Algorithms

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Binary search algorithm

Semantic Analysis: Types and Type Checking

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

El Dorado Union High School District Educational Services

5. Binary objects labeling

CSI33 Data Structures

Common Data Structures

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Operating Systems. Virtual Memory

Introduction to Data Structures

16 Collection Classes

The C Programming Language course syllabus associate level

A Catalogue of the Steiner Triple Systems of Order 19

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Moving from CS 61A Scheme to CS 61B Java

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

C++FA 5.1 PRACTICE MID-TERM EXAM

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Chapter 7: Software Development Stages Test your knowledge - answers

Cpt S 223. School of EECS, WSU

Data Structures and Data Manipulation

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

10CS35: Data Structures Using C

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS/COE

DATA STRUCTURE - QUEUE

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Data Structures. Level 6 C Module Descriptor

Comp151. Definitions & Declarations

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

Answers to Review Questions Chapter 7

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

Algorithms and Abstract Data Types

BCS2B02: OOP Concepts and Data Structures Using C++

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER


Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Data Structures. Algorithm Performance and Big O Analysis

N3458: Simple Database Integration in C++11

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Analysis of a Search Algorithm

TivaWare Utilities Library

Notes from Week 1: Algorithms for sequential prediction

Transcription:

Cours de C++ Utilisations des conteneurs Cécile Braunstein cecile.braunstein@lip6.fr 1 / 18

Introduction Containers - Why? Help to solve messy problems Provide useful function and data structure Consistency between containers Containers Collection of objects Defined with the template classes : Seperate the containerfrom the type of the data inside. Each containers type is optimized for a specific use (access/modification). Main containers : list, vector, stack, queue, map 2 / 18

Example : vector Action Insert an element Remove an element Remove all elements Returns a value that denotes the first element Returns a value that denotes (one past) the last element Returns a value that denotes the i th element Take the vector size Check emptiness Method v.push_back() v.pop_back() v.clear() v.begin() v.end() v[i] v.size() v.empty() Attention : The first element is indexed by 0 and the last by size-1. 3 / 18

Container s type list Insert and remove anywhere in constant time Automatic memory management vector General purpose Fast access by index (constant time) Insert and remove an element at the end in constant time Other insert and remove in linear time set, map Access an element by a key in constant time Fast search of an element 4 / 18

Container s properties Containers have their own elements Elements of a container have to support the copy and assigment instruction (=) All containers have a method empty() and size() in constant time All containers have a method begin() and end() 5 / 18

Containers constructors container<t> c; container<t> c(c2); container<t> c(n); container<t> c(n,t); container<t> c(b,e); Empty container Copy of c2 With n elements value-initialized according to T With n elements copies of t Copy of the elements an other container between [b,e) 6 / 18

How to choose? What is the purpose? How we want ot access the element (randomly, in one order...) Which modification on the collection of data (add/remove elements, sort...) Programm performance Access time/ Modification time Time depends on the number of elements Types of times : linear, log, exponential... Memory usage... 7 / 18

How to access element? Iterator Purpose Pointer generalization Use for a sequential access to elements Optimisation regarding the container s type Iterator Definition An iterator is a value that Identifies a container and an element in the container Lets us examine the value stored in that element Provides operations for moving between elements in the container Restricts the available operations to correspond to what the container can handle efficently 8 / 18

First example vector<double> v; //v is full vector<double>::size_type i; for(i = 0; i!= v.size(); ++i) { cout << v[i] << endl; } vector<double> v; //v is full vector<double>::iterator iter; for(iter = v.begin(); iter!= v.end(); ++iter) { cout << *iter << endl; } 9 / 18

Iterator Most general types Every standard container defines two iterator types : container-type : :iterator container-type : :const_iterator Operations Comparison (, =...) Incrementation Dereference Every operations that modify the containers invalid the iterator 10 / 18

Associative containers Goal What happen if we want to find a given value into a sequential containers? Look at each element one by one Sort the container and use a fast search algorithm Both solutions are quite slow or need sophistical algorithm Alternative : using associative containers Arrange elements that depends on the value of the element Exploit the ordering to locate element quickly It contains more information : key 11 / 18

Associative Array map example < key, value > When we put this pair into the data structure, the key will be associate to this value until we delete the pair. Works as vector But Key doesn t need to be an integer ; it can be any value that we can compare in order to keep them ordered Unique key values Associative containers is self-ordering : our program must not change the order of elements 12 / 18

Using associative containers The class pair Simple data structure that holds to element : first and second Each element of map is a pair first : key ; second : the associated value Iterator For a map with a key of type K and a value of type T the associated pair is : pair<const K, T> Access the key and the value with an iterator is : map<char,value>::iterator ite; ite->first; ite->second; 13 / 18

Compare fonction How to compare keys? When built-in type or type with comparaison function : use the defined ones When no comparaison exists : programmer have to write one map<k,v> m; map<k,v,t_fpt> m(fpt); map<k,v,comp> m; Empty map with keys of type const K and value of type V Map with the comparaison function as pointer function fpt with the prototype T_fpt Map with a comparison object to be used for the ordering 14 / 18

Main operations map<key,t> begin end empty size operator[] insert erase find lower_bound upper_bound declaration Return iterator to beginning Return iterator to end Test whether container is empty Return container size Access element Insert element Erase elements Get iterator to element Return iterator to lower bound Return iterator to upper bound 15 / 18

Use of an associative container map<string,double> m; m["abie"] = 2.5; m["sarah"] = 6.8; m["michael"]= 7.5; m.insert(pair<string,double>("thomas",5.2)); map<string,double>::iterator it; for(map<string,double>::iterator it = m.begin(); it!= m.end(); ++it) { cout << it->first << "\t" << it-> second << endl; } 16 / 18

Use of an associative container-constructor 1/2 bool compare(const string& s1, const string& s2) { return s1.size() >= s2.size(); } int main() { bool(*fn_pt)(const string&,const string&) = compare; map<string,double,bool(*)(const string&, const string &)> m(fn_pt);... } 17 / 18

Use of an associative container-constructor 2/2 struct classcomp { bool operator() (const string& s1, const string& s2) const {return s1.size() <= s2.size();} }; int main() { map<string,double,classcomp> m;... } 18 / 18