Utente:Embolo/Sandbox

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca

STL[modifica | modifica wikitesto]

la Standard Template Library (STL) è una Libreria software inclusa nella Standard Library del linguaggio C++ e definisce Strutture dati generiche, Iteratori e Algoritmi generici.

Descrizione[modifica | modifica wikitesto]

La STL è stata implementata nel linguaggio C++ il massiccio utilizzo dei templates.

In pratica lo standard (ISO/IEC 14882) non richiede alle software houses che sviluppano i compilatori, a differenza delle librerie standard del C e del C++, di generare una libreria con codice oggetto cui linkare i programmi che la utilizzano, ma segue un'altra via: le classi e le funzioni non sono dei "prodotti finiti", ma poco più che degli schemi; al momento dell'istanziamento di un oggetto o funzione template, tramite una sintassi particolare, possono essere specificati dei parametri (ad esempio, il tipo che deve essere contenuto in una struttura dati, o la funzione utilizzata per allocare memoria, etc.) utilizzati di volta in volta dal compilatore per generare in linea il codice finale per quell'oggetto, che quindi verrà in un secondo momento convertito in codice oggetto (binario).

Questo tipo di approccio è molto potente e genera codice più efficiente di quello ottenuto attraverso il meccanismo dell'ereditarietà; lo svantaggio è nella generazione del codice, che può risultare molto complesso, tanto da creare talvolta problemi ai compilatori, ai quali può succedere di fallire la compilazione di costrutti validi, di produrre codice non valido, o richiedere al programmatore sforzi ulteriori (non richiesti, in teoria, dallo standard) per ottenere il risultato voluto.

La Standard Template Library è stata la prima libreria a contenere algoritmi e strutture dati generici, seguendo quattro concetti base: programmazione generica, astrattezza senza perdita di efficienza, il modello computazionale di Von Neumann, and value semantics.


Contenuti[modifica | modifica wikitesto]

Containers[modifica | modifica wikitesto]

La STL contiene containers sequenziali e associativi. Tra i containers sequenziali troviamo: vector, string e deque. I containers associativi standard sono set, multiset, map e multimap.

vector - è un tipo di array C-like (cioè consente l'accesso casuale) la capacità di ridimensionarsi automaticamente all'atto dell'inserimento o della cancellazione di un oggetto. Inserting and removing an element to/from back of the vector at the end takes constant time. Inserting and erasing at the beginning or in the middle is linear in time.

deque (double ended queue) - a vector with insertion/erase at the beginning in amortized constant time, however lacking some guarantees on iterator validity after altering the deque.

set - inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides set operations union, intersection, difference, symmetric difference and test of inclusion.

Libraries implementing STL often include hashed variants: hash_set, hash_multiset, hash_map and hash_multimap, however this extension is not part of standard and are defined in various namespaces among implementations as a result.

Iterators[modifica | modifica wikitesto]

The STL implements five different types of iterators. These are input iterators, output iterators, forward iterators, bidirectional iterators and random access iterators.

Functors[modifica | modifica wikitesto]

The STL includes classes that overload the function operator (operator()). Classes that do this are called functor classes or function classes. They are useful for keeping and retrieving state information in functions passed into other functions.


Storia[modifica | modifica wikitesto]

L'architettura della STL è stata creata in buona parte da Alexander Stepanov. Nel 1979 cominciò ad implementare le sue idee iniziali sulla Programmazione generica, esplorando le sue potenzialità, rivoluzionarie nel campo dello sviluppo del software. Anche se Dave Musser aveva già sviluppato precedentemente alcuni aspetti della programmazione generica nel 1971, i suoi contributi furnono limitati ad una area molto specializzata dello sviluppo software, la (computer algebra).

Stepanov riconobbe il pieno potenziale della programmazione generica e persuase i suoi allora colleghi della General Electric Research and Development (tra i quali, principalmente, Dave Musser e Deepak Kapur) che la programmazione generica should be pursued as a comprehensive basis for software development. A quei tempi non esisteva un supporto reale alla programmazione generica in nessun linguaggio di programmazione.

Il primo linguaggio di una certa importanza a dare tale supporto fu il Linguaggio di programmazione Ada, con le sue generic units. Dal 1987 Stepanov e Musser svilupparono e distribuirono una libreria Ada per il processamento di liste che racchiudeva i risultati di buona parte delle loro ricerche sulla programmazione generica. Comunque, l'Ada non ha mai avuto molta diffusione al di fuoari dell'industria della difesa e il C++ sembrava avere migliori possibilità di diffusione e di provvedere un buon supporto alla programmazione generica anche se il linguaggio era ancora relativamente immaturo (ancora non supportava i templates, aggiunti solo in un secondo momento). Un'altra ragione che ha spinto verso l'utilizzo del C++, che Stepanov riconobbe quasi subito, fu il modello computazionale del C/C++ che consente un accesso molto flessibile alla memorizzazione attraverso i puntatori, cruciale per ottenere genericità senza perdere in efficienza.

Furono necessarie molte ricerche e sperimentazioni, non solo per sviluppare i singoli componenti, ma per sviluppare un'architettura completa per una libreria di componenti basata sulla programmazione generica. Prima ai AT&T Bell Laboratories e in seguito alla Hewlett-Packard Research Labs, Stepanov sperimentò molte furmulazioni architettulare e algoritmiche, prima in C e in seguito in C++. Musser collaborò a questa ricerca e nel 1992 Meng Lee entrò a far parte del progetto di Stepanov alla HP e ne divenne uno dei principali contributor.

This work undoubtedly would have continued for some time as just a research project or at best would have resulted in an HP proprietary library if Andrew Koenig of Bell Labs had not become aware of the work and asked Stepanov to present the main ideas at a November 1993 meeting of the ANSI/ISO committee for C++ standardization. The committee's response was overwhelmingly favorable and led to a request from Koenig for a formal proposal in time for the March 1994 meeting. Despite the tremendous time pressure, Alex and Meng were able to produce a draft proposal that received preliminary approval at that meeting.

The committee had several requests for changes and extensions (some of them major), and a small group of committee members met with Stepanov and Lee to help work out the details. The requirements for the most significant extension (associative containers) had to be shown to be consistent by fully implementing them, a task Stepanov delegated to Musser. It would have been quite easy for the whole enterprise to spin out of control at this point, but again Stepanov and Lee met the challenge and produced a proposal that received final approval at the July 1994 ANSI/ISO committee meeting. (Additional details of this history can be found in an interview Alexander Stepanov gave in the March 1995 issue of Dr. Dobb's Journal.)

Subsequently, the Stepanov and Lee document 17 was incorporated into the ANSI/ISO C++ draft standard (1, parts of clauses 17 through 27). It also influenced other parts of the C++ Standard Library, such as the string facilities, and some of the previously adopted standards in those areas were revised accordingly.

In spite of STL's success with the committee, there remained the question of how STL would make its way into actual availability and use. With the STL requirements part of the publicly available draft standard, compiler vendors and independent software library vendors could have course develop their own implementations and market them as separate products or as selling points for their other wares. One of the first edition's authors, Atul Saini, was among the first to recognize the commercial potential and began exploring it as a line of business for his company, Modena Software Incorporated, even before STL had been fully accepted by the committee.

The prospects for early widespread dissemination of STL were considerably improved with Hewlett-Packard's decision to make its implementation freely available on the Internet in August 1994. This implementation, developed by Stepanov, Lee, and Musser during the standardization process, became the basis of all implementations offered by compiler and library vendors today.

References[modifica | modifica wikitesto]

External links[modifica | modifica wikitesto]



Iteratore[modifica | modifica wikitesto]

Nella Programmazione orientata agli oggetti, un iteratore è un oggetto che permette di percorrere tutti gli elementi di un altro oggetto, tipicamente un container o una lista. Viene talvolta definito anche cursore.


, specialmente nell database.

Descrizione[modifica | modifica wikitesto]

Un iteratore può essere pensato come un tipo di puntatore con due funzioni principali: referenziare un dato elemento del collection object (detto element access), e modificare se stesso in modo da puntare al prossimo elemento (called element traversal). Deve essere definita anche una "Jigar Rules" way per creare un iteratore in modo che punti al primo elemento della sequenza, così come un modo per determinare quando questa sequenza è terminata. Depending on the language and intended use, iterators may also provide additional operations or exhibit different behaviors.

The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list. An iterator class is usually designed in tight coordination with the corresponding container class. Usually the container provides the methods for creating iterators.

Contrasting with indexing[modifica | modifica wikitesto]

In procedural languages it is common to use indexing to loop through all the elements in a sequence such as an array. Although indexing may also be used with some object-oriented containers, the use of iterators may have advantages.

  • Counting loops are not suitable to all data structures, in particular to data structures with no or slow random access, like lists or trees.
  • Iterators can provide a consistent way to iterate on data structures of all kinds, and therefore make the code more readable, reusable, and less sensitive to a change in the data structure.
  • An iterator can enforce additional restrictions on access, such as insuring that elements can not be skipped or that a previously visited element can not be accessed a second time.
  • An iterator may allow the container object to be modified without invaliding the iterator. For instance, once an iterator has advanced beyond the first element it may be possible to insert additional elements into the beginning of the container with predictable results. With indexing this is problematic since the index numbers must change.

The ability of a container to be modified while iterating through its elements has become necessary in modern object-oriented programming, where the interrelationships between objects and the effects of operations may not be obvious. By using an iterator one is isolated from these sorts of consequences.

Implicit iterators[modifica | modifica wikitesto]

Some object-oriented languages such as Perl or Python provide an intrinsic way of iterating through the elements of a container object without the introduction of an explicit iterator object. This is often manifested by some sort of "for-each" operator, such as in the following examples:

   # Perl, implicit iteration
   foreach $val (@list) {
       print "$val\n";
   }
   # Python, implicit iteration
   for Value in List:
       print Value

The C++ language also has a std::for_each() function template which allows for similar implicit iteratation, but it still requires explicit iterator objects as initial input.

Generators[modifica | modifica wikitesto]

A generator is a special kind of iterator in which the container object is not fully realized. This allows abstract or even infinite collections to be processed one element at a time. Generators are common in functional programming languages, or languages which borrow some functional concepts. Generators are often implemented in terms of continuations.

Iterators in different programming languages[modifica | modifica wikitesto]

C++[modifica | modifica wikitesto]

The C++ language makes wide use of iterators in its Standard Template Library. All of the standard container template types provide a rich and consistent set of iterator types. The syntax of standard iterators is designed to resemble that of ordinary C pointer arithmetic, where the * and -> operators are used to reference the element to which the iterator points, and pointer arithmetic operators like ++ are used to advance the iterator to the next element.

Iterators are usually used in pairs, where one is used for the actual iteration and the second serves to mark the end of the collection. The iterators are created by the corresponding container class using standard methods such as begin() and end(). The iterator returned by begin() points to the first element, while the iterator returned by end() is a special value that does not reference any element.

When an iterator is advanced beyond the last element it is by definition equal to the special end iterator value. The following example shows a typical use of an iterator.

   ContainerType  C;  // Any standard container type, like std::list<sometype>
   ContainerType::iterator A = C.begin();
   ContainerType::iterator Z = C.end();
   while( A != Z ) {
       ContainerType::value_type  value = *A;
       std::cout << value << std::endl;
       ++A;
   }

There are many varieties of iterators each with slightly different behavior, including: forward, reverse, and bidirectional iterators; random-access iterators; input and output iterators; and const iterators (which protect the container or its elements from modification). However not every type of container supports every type of iterator. It is possible for users to create their own iterator types by deriving subclasses from the standard std::iterator class template.

Iterator safety is defined separately for the different types of standard containers, in some cases the iterator is very permissive in allowing the container to change while iterating.

Java[modifica | modifica wikitesto]

Introduced in the Java 1.2 standard, the java.util.Iterator interface allows one to iterate container classes. Each Iterator provides a next() and hasNext() method, and may optionally support a remove() method. Iterators are created by the method iterator() provided by the corresponding container class.

The next() method will advance the iterator and then return the value pointed to by that iterator. When first created an iterator points to a special value before the first element, so that the first element is obtained upon the first call to next(). To determine when all the elements in the container have been visited the hasNext() test method is used. The following example shows a simple use of iterators:

   Iterator it = list.iterator();
   while (it.hasNext()) {
       Object val = it.next();
       System.out.println(val.toString());
   }

For collection types which support it, the remove() method of the iterator may be used to remove the most recently visited element from the container. Most other types of modification to the container while iterating are unsafe.

Python[modifica | modifica wikitesto]

Iterators in Python are a fundamental part of the language and in many cases go unseen as they are implicitly used with the for-statement. All of Python's standard built-in sequence types support iteratation, as well as many classes which are part of the standard library. The following example shows typical implicit iteration over a sequence:

   for value in sequence:
       print value

Iterators however can be used and defined explicitly. For any iteratable sequence type or class, the builtin function iter() is used to create an iterator object. The iterator object then provides a next() method which returns the next element in the container. It will raise a StopIteration error when no more elements are left. The following example shows an equivalent iteration over a sequence using explicit iterators:

   it = iter(sequence)
   try:
       while True:
           print it.next()
   except StopIteration:
       pass

Any user defined class can support standard iteration (either implicit or explicit) by defining an __iter__() method which creates an iterator object. The iterator object then needs to define a next() method which returns the next element..

Python also supports generators, which are a special type of iterator over some unrealized collection. A generator is a '"frozen" function. After each value is yielded, the state of the function is frozen until it is called again, at which point execution resumes from where the 'yield' statement left off, with all function variables as they were at the previous call. Here is an example of a generator that returns each number of the Fibonacci sequence:

   def fibo_gen():
       x = 0
       y = 1
       while True:
           yield x
           x, y = y, x+y

See also[modifica | modifica wikitesto]

External links[modifica | modifica wikitesto]