Basic memo: STL basic example

Source: Internet
Author: User

Relationship between C ++ standard library and STL

1. Getting started with STL

In a broad sense, STL code is divided into three types: algorithm (algorithm), container (container), and iterator (iterator). Almost all the Code uses the template class and template function, this provides a better chance of code reuse than a traditional library composed of functions and classes.

In the C ++ standard, STL is organized as the following 13 header files: <Algorithm>, <deque>, <functional>, <iterator>, <vector>, <list>, <map>,

<Memory>, <numeric>, <queue>, <set>, <stack>, and <utility>.

Example 1

# Include <vector> // contains the header file # include <iostream> using namespace STD; int main () {vector <double> A; // defines the data variable vector <double> :: const_iterator I; // defines the variable. push_back (1); // call the function a in STL. push_back (2);. push_back (3);. push_back (4);. push_back (5); for (I =. begin (); I! = A. End (); I ++) // cyclic output {cout <(* I) <Endl ;}system ("pause ");}

Result:

In the above Code, push_back (), begin (), and end () functions are used. These functions are not defined in the program, but can be used, this is because these functions have been header file vector. h. If strcpy () is string. h contains the same.

Example 2.

# Include <vector> # include <cstdlib> # include <algorithm> # include <iostream> using namespace STD; Template <class T> struct print {void operator () (T & X) const // const indicates that this member function does not modify the data member of the class {If (0 = x % 2) {cout <x <'';}}; int main (INT argc, char * argv []) {vector <int> vcints; For (INT I = 0; I <10; I ++) {vcints. push_back (I) ;}vector <int>: iterator iterbegin, iterend; // defines two iterators, which are used to scatter the beginning and end of the container iterbegin = vcints. begin (); Iterend = vcints. End (); cout <"output all elements:" <Endl; For (; iterbegin! = Iterend; ++ iterbegin) // traverse {cout <* iterbegin <";}// output cout <Endl; cout <" output even element: "<Endl; iterbegin = vcints. begin (); // redirect start position for_each (iterbegin, iterend, print <int> ()); // use the for_each algorithm and function object print to output the cout element in the container <Endl; System ("pause"); Return 0 ;}

Result
The preceding Code overload the bracket operator "()", so it can be used as a function object. The iterbegin and iterend iterators point to the start and end of the container respectively. The two iterators can be used to traverse the entire container. Finally, the for_each algorithm is called and the function object print is used in combination. The for_each action is similar to the for loop.

2. Algorithm

The algorithm in STL consists of the header file <algorithm>, <numeric>, and <functional>. Example:

# Include <iostream> # include <algorithm> # include <functional> # include <vector> using namespace STD; Class myclass {public: myclass (int A, int B ): first (a), second (B) {}int first; int second; bool operator <(const myclass & M) const // overload operator <{return first <m. first ;}}; bool less_second (const myclass & M1, const myclass & m2) // according to the ratio of 2nd elements {return m1.second <m2.second;} int main () {int I = 0; vector <myclass> VCT; for (I = 0; I <10; I ++) {myclass my (10-i, I * 3); VCT. push_back (my);} for (I = 0; I <VCT. size (); I ++) cout <"(" <VCT [I]. first <"," <VCT [I]. second <")" <Endl; sort (VCT. begin (), VCT. end (); // sort cout by 1st values <"after sorted by the first:" <Endl; for (I = 0; I <VCT. size (); I ++) cout <"(" <VCT [I]. first <"," <VCT [I]. second <")" <Endl; // output the result of sorting by 1st values sort (VCT. begin (), VCT. end (), less_second); // sort cout by 2nd values <"after sorted by the second:" <Endl; for (I = 0; I <VCT. size (); I ++) cout <"(" <VCT [I]. first <"," <VCT [I]. second <")" <Endl; // output the result of sorting by 2nd values: System ("pause"); Return 0 ;}

Result

3. Container

The container consists of header files <vector>, <list>, <deque>, <set>, <map>, <stack>, and <queue>.

3.1 container -- Vector)

Example 1

# Include <iostream> # include <vector> using namespace STD; char * szhw = "Hello World"; int main (INT argc, char * argv []) {vector <char> VCT; // declare a Character Vector vector <char>: iterator VI; // define a cursor iterator char * cptr = szhw for the character array; while (* cptr! = '\ 0') // initialize the Character Vector to loop the entire string and place the data in the Character Vector until {VCT ends when' \ 0' is encountered. push_back (* cptr); cptr ++;} // push_back place the data at the end of the vector for (Vi = VCT. begin (); vi! = VCT. End (); vi ++) // display characters in the vector one by one on the console. This is the beginning of STL loop normalization, usually "! = ", Instead of" <", because" <"does not define cout in some containers <* VI; // use the operator "*" to extract data from the cursor cout <Endl; System ("pause"); Return 0 ;}

In the preceding example, the vector <vector> container class is used. About half of STL containers are vector-based. In fact, vector is a dynamic array and a class template for basic arrays. Many basic operations are defined internally. Since this is a class, it will have its own constructor. The precompiled header file is # include <vector>.

Example 2. You can also access the vector element like an array, as shown below:

# Include <vector> # include <iostream> using namespace STD; int main () {vector <int> A; For (INT I = 0; I <10; I ++) // here I is int type data, not iterator. push_back (I * I); For (INT I = 0; I <. size (); I ++) // use the function size () to obtain the size of container A. cout <A [I] <""; // access the cout element of the vector using arrays <Endl; System ("pause"); Return 0 ;}

Example 3 search for elements with specific values in the container and display the subscript position

# Include <vector> # include <string> # include <iostream> using namespace STD; int main () {vector <int> A (10); vector <int> :: iterator I; A [5] = 100; // set a [5] to 100 for (I =. begin (); I! =. End (); I ++) cout <* I <""; cout <Endl; vector <int>: iterator intiter = find (. begin (),. end (), 100); // find the iterator with a value of 100 if (intiter! = A. End () // the pointer returned by end is not the element of the last position. Is the last element pointer + 1 {cout <"found:" <* intiter <Endl; cout <"Location:" <intIter-a.begin () <Endl; // subscript position: the initial position before the current position of the iterator. } Else cout <"not found" <Endl; System ("pause"); Return 0 ;}

The following four constructors are defined in vector:

1) default constructor

Construct an empty vector with an initial length of 0. The call format is as follows:

Vector <int> V1;

2) constructor with unit Integer Parameters

This parameter describes the initial size of a vector. This constructor also has an optional parameter. This is an instance of type T and describes the initial values of each member in each vector, its call is as follows (T is int at this time ):

Vector <int> V2 (init_size, 0); // You must define init_size in advance to indicate the initial size of the vector. All its members are initialized to 0.

3) constructor with two constant parameters

Generate a vector with an initial value as an interval. The interval is specified by a semi-open interval [first, last). The call format is as follows:

Vector <int> V3 (Firs, last );

Note: In the STL system, all iterators that use a pair of iterators are left closed and right open, [begin (), end ()). The returned end is not the pointer to the element at the last position, but the pointer to the last element + 1.

4) copy constructor

Construct a new vector as a complete copy of an existing vector. Its call is as follows:

Vector <int> V4 (V3 );

In addition, many member functions of vector classes are used in actual programs. The commonly used member functions are as follows.

Begin (), end (), push_back (), insert (), assign (), Front (), back (), erase (), empty (), (), size ().

3.2 containers -- list

The list is also a type of container class. The series whose length is n is stored in a two-way linked list with N nodes. It supports two-way iterators, its pre-compiled header file is # include <list>

Another feature of the template list is in exception handling. For any container, the exception thrown by the container member function during execution puts the container itself in a consistent state and can be destroyed, in addition, the container does not lose control of the allocated storage space. However, for most operations, especially those that can affect multiple elements, the precise state of the container is not specified when an exception is thrown, but the list ensures that an exception is thrown for most member functions, the container can be restored to the status before the operation. The List class is defined as follows:

List <t, Allocator <t> ls; // use the default template parameters. You can omit 2nd parameters.

The member functions are as follows: resize () Clear () Front () Back () push_back () push_front () pop_back () pop_front () Assign () insert () Erase () splice () remove () remove_if () Unique () sort () Merge () reverse ().

# Include <list ># include <iostream> int main () {using namespace STD; List <int> C1; List <int >:: iterator c1_iter; c1.push _ back (20); c1.push _ back (10); c1.push _ back (30); cout <"Before sorting C1 ="; for (c1_iter = c1.begin (); c1_iter! = C1.end (); c1_iter ++) // output the cout <"" <* c1_iter; cout <Endl; c1.sort (); // call the list sorting function cout <"after sorting C1 ="; for (c1_iter = c1.begin (); c1_iter! = C1.end (); c1_iter ++) // output the sorted content cout <"" <* c1_iter; cout <Endl; c1.sort (greater <int> ()); // call the descending sort function cout <"after sorting with 'Greater thance' operation, C1 ="; for (c1_iter = c1.begin (); c1_iter! = C1.end (); c1_iter ++) // output the sorted content cout <"" <* c1_iter; cout <Endl; System ("pause "); return 0 ;}

Result

3.3 containers -- Set

Set is also a type of container. Its feature is that the element value in the set isUnique. In the collection, all members areArranged. If you insert:, to a set successively, the output time is.

#include<iostream>#include<set>#include<string>using namespace std;int main(){    set <string> strset;    set <string> ::iterator si;    strset.insert("Apple");    strset.insert("Bnana");    strset.insert("Orange");    strset.insert("Plate");    strset.insert("Grapes");    strset.insert("Grapes");    for(si=strset.begin();si!=strset.end();si++)       cout<<*si<<" ";    cout<<endl;    system("pause");    return 0;    }

In the preceding example, although grapes is inserted twice, the same element only appears once.

3.4 containers-Dual-end queue

A dual-end queue is a queue container class, which is defined in the header file deque (Double Queue ). When using this container, add the following statement to the header file: # include <deque>

Similar to vector: supports random access and fast insertion and deletion. linear time is used for operations at a certain position in the window.

Different from Vector: deque also supports data insertion from the start, because it contains the push_front () function for data insertion at the start (). In addition, deque does not support capacity () and reserve () operations similar to vector. Example 1:

# Include <iostream> # include <deque> using namespace STD; typedef deque <int> intdeque; void put_deque (intdeque deque, char * name) // display all the deque elements from the beginning and back {intdeque: iterator pdeque; cout <"the contents of" <name <":"; for (pdeque = deque. begin (); pdeque! = Deque. end (); pdeque ++) cout <* pdeque <"; cout <Endl ;}int main () {intdeque deq1; intdeque deq2 ); put_deque (deq1, "deq1"); put_deque (deq2, "deq2"); deq1.push _ back (2); // Add the deq1.push _ back (4) element after the deq1 sequence ); cout <"deq1.push _ back (2) and deq1.push _ back (4):" <Endl; put_deque (deq1, "deq1"); deq1.push _ Front (5 ); // Add the element deq1.push _ Front (7) before the deq1 sequence; cout <"deq1.push _ Front (5) and deq1.push _ Front (7):" <Endl; put_deque (deq1, "deq1"); deq1.insert (deq1.begin () + 1, 3, 9); // insert data cout In The Middle Of deq1 <"deq1.insert (deq1.begin () + 1, 3, 9): "<Endl; put_deque (deq1," deq1 "); cout <" deq1.at (4) = "<deq1.at (4) <Endl; // test the reference class function cout <"deq1 [4] =" <deq1 [4] <Endl; deq1.at (1) = 10; deq1 [2] = 20; cout <"deq1.at (1) = 10 and deq1 [2] = 20:" <Endl; put_deque (deq1, "deq1"); deq1.pop _ Front (); // deq1.pop _ back (); cout <"deq1.pop _ Front () and deq1.pop _ back ():" <Endl; put_deque (deq1, "deq1"); deq1.erase (deq1.begin () + 1); // clear the 2nd cout elements in deq1 <"deq1.erase (deq1.begin () + 1 ): "<Endl; put_deque (deq1," deq1 "); deq2.assign (8, 1); // assign values to deq2 and display cout <" deq2.assign (8, 1): "<Endl; put_deque (deq2, "deq2"); System ("pause"); Return 0 ;}

Example 2

# Include <deque> # include <string> # include <iostream> using namespace STD; int main () {deque <string> A; string word; For (INT I = 0; I <5; I ++) {CIN> word;. push_back (Word);}. pop_front (); // delete an element a from the front. pop_back (); // delete an element for (INT I = 0; I <. size (); I ++) // use the function size () to obtain the size of container a cout <A [I] <""; // access the deque element cout in array mode <Endl; System ("pause"); Return 0 ;}

3.5 container -- Stack

A container stack is a special type of container. Its feature is post-import, first-out. You can perform the following five operations:

Empty (): If the stack is empty, true is returned; otherwise, false is returned.

Size (): returns the number of elements in the stack.

Pop (): delete, but do not return the top element of the stack.

Top (): return, but do not delete the top element of the stack.

Push (): add the elements at the top of the new stack.

# Include <stack> # include <iostream> using namespace STD; int main () {const int ia_size = 10; int Ia [ia_size] = {, 6, 7, 8, 9}; int IX = 0; stack <int> intstack; For (; ix <ia_size; ++ IX) intstack. push (IA [ix]); // If (intstack. size ()! = Ia_size) {cout <"error" <Endl; Return-1 ;}int value; while (! Intstack. empty () {value = intstack. top (); // get the cout element at the top of the stack <value <Endl; intstack. pop (); // Delete the top element of the stack} system ("pause"); Return 0 ;}

3.6 containers- ing and multi- ing

Ing and multi- ing are used to quickly and efficiently search data. Similarly, to use ing and multi- ing containers in a program, add the following header files: # include <map>

Ing map supports the subscript operator []. You can access map by accessing common data, or the subscript is the map key. In mutimap, a key can correspond to multiple different values.

# Include <map> # include <iostream> using namespace STD; int main () {Map <char, Int, less <char> map1; Map <char, Int, less <char >>:: iterator mapiter; map1 ['C'] = 3; // initialization, similar to array. You can also use map1.insert (Map <char, Int, less <char >>:: value_type ('C', 3); map1 ['D'] = 4; map1 ['a'] = 1; map1 ['B'] = 2; for (mapiter = map1.begin (); mapiter! = Map1.end (); mapiter ++) cout <(* mapiter ). first <":" <(* mapiter ). second <"; cout <Endl; Map <char, Int, less <char >:: const_iterator PTR; PTR = map1.find ('D '); // retrieve the cout value corresponding to the d key <(* PTR ). first <"key corresponds to value:" <(* PTR ). second <Endl; System ("pause"); Return 0 ;}

4. iterator

The iterator is actually a generalized pointer. If an iterator points to a member in the container, the iterator can traverse all the members in the container through auto-increment and auto-subtraction. An iterator is a media used to connect containers and algorithms. It is an interface used to operate containers by algorithms.

The iterator in STL mainly consists of the header file <utility>, <iterator>, and <memory>.

<Utility> includes several template declarations used throughout STL.

<Iterator> the header file provides many methods used by the iterator.

<Memory> the main part of the header file is the template class Allocator, which is responsible for generating default splitters in all containers.

For example, the following program outputs the content of a file to the screen using the input/output iterator.

# Include <iostream> # include <fstream> # include <iterator> # include <vector> # include <string> using namespace STD; int main () {vector <string> V1; ifstream file ("test.txt"); If (file. fail () {cout <"failed to open the file. Make sure the file to be opened exists." <Endl;} copy (istream_iterator <string> (file ), istream_iterator <string> (), inserter (V1, v1.begin (); // if there is no # include <iterator>, an error is reported here: Copy (v1.begin (), v1.end (), ostream_iterator <string> (cout, ""); cout <Endl; System ("pause"); Return 0 ;}

In the above Code, the input iterator istream_iterator and the output iterator ostream_iterator are used. The program completes the function of outputting a file to the screen, first reads the file, then copies the file content to the vector container of the string type through the iterator, and finally outputs the iterator output. Inserter is an input iterator function (iterator adapter), which is used as follows:

Inserter (container, POS );

Comprehensive example: the rescue scope of the program below is 2 ~ All prime numbers in n, where n is input by the keyboard when the program is running. The implementation code is as follows.

# Include <iostream> # include <iomanip> // Io control flow header file # include <vector> using namespace STD; int main () {vector <int> A (10 ); int N; int primecount = 0, I, j; cout <"enter a value> 2 as upper limit:"; CIN> N; A [primecount ++] = 2; for (I = 3; I <n; I ++) {If (primecount =. size () // reaches the vector size. resize (primecount + 10); // call the function to reset the vector size if (I % 2 = 0) // not a prime number continue; j = 3; while (j <= I/2 & I % J! = 0) // cyclically determine whether it is a prime number J + = 2; // variable increments 2 if (j> I/2) // is the prime number a [primecount ++] = I; // write vector} for (I = 0; I <primecount; I ++) {cout <SETW (5) <A [I]; // set the output format and output if (0 = (I + 1) % 10) // 10th rows output a line feed cout <Endl ;} cout <Endl; System ("pause"); Return 0 ;}


The preceding Code uses a vector container to store prime numbers. This program uses the cyclic remainder method to obtain the range of 2 ~ All prime numbers in N.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.