C++STL basic knowledge of generic programming explained--------February 3, 2015

Source: Internet
Author: User
Tags set set

Today I learned the basics of c++stl generic programming, and I organized the main knowledge as follows:

STL provides three types of components: containers, iterators, algorithms. Supports generic program design standards.
There are two main types of containers: sequential containers and associative containers.
Sequential containers: Vector,list,deque,string are a collection of successive elements.
Associative container: Set,multiset,map,multimap contains the key value of the lookup element.
Iterators: Traversing containers
STL algorithm Library: Sorting algorithm, non-variable order algorithm, variable order algorithm, numerical algorithm.


/******************************************************************************************************* /
Introduction to Vector container
(1) Advantage: You can randomly access individual elements and add elements at the end. So you can completely replace the array. With memory automatic management function, can dynamically adjust the memory function at any time.
(2) Basic content
Header file declaration: #include <vector> the
Vector container is counted from subscript 0, we can fix a size beforehand, we can resize it at any time afterwards, or you can use Push_ at any time without defining it beforehand. The back () method expands from the tail, or you can insert an element before an element position by using the Insert () method.
Two important methods of vector containers:
Begin () and End (): The Begin () method returns an iterator to the position of the first element, and the end () method returns the position of the next element of the last element.
(3) Create object
method 1:vector<int>v;
2:vector<double>v (10); (fixed size)
Method 3:vector<double>v ( 10,8.6); (fixed size and initialize)
(3) The tail extension of the element
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
Vector<int>v;
V.push_back (2);
V.push_back (7);
V.push_back (9);
return 0;
}

(4) Subscript access vector elements
#include <iostream>
#include <vector>
using namespace Std;
int main ()
{
Vector<int>v (3);
v[0]=2;
v[1]=7;
v[2]=9;
cout<<v[0]<<v[1]<<v[2]<<endl;
return 0;
}
(5) using iterators to access vector elements
The type of the iterator must be the same type as the element of the traversed vector object
#include <iostream>
#include <vector>
using namespace Std;
int main ()
{
vector<int>v;
V.push_back (3);
V.push_back (6);
V.push_back (9);
Vector<int>::iterator it;
For (It=v.begin (); It!=v.end (); it++)
{
cout<<*it<<endl;
}
return 0;
}

(6) Insertion of elements
The Insert () method inserts a new element before any position in the vector object, and the vector automatically expands the space of an element, and all the elements move backward one position after the insertion position.
#include <iostream>
#include <vector>
using namespace Std;
int main ()
{
Vector<int>v (3);
V[0]=1;
v[1]=3;
v[2]=6;
V.insert (V.begin (), 8);
V.insert (V.begin () +2;9);//Insert Element 9 before the second element
For (It=v.begin (); It!=v.end (); it++)
{
cout<<*it<<endl;
}
return 0;
}
(7) Deletion of elements
The erase () method can remove all elements of an element or interval that an iterator in the vector refers to. The clear () method can delete all elements.
#include <iostream>
#include <vector>
using namespace Std;
int main ()
{
Vector<int>v (3);
V[0]=1;
v[1]=3;
v[2]=6;
V.erase (V.begin () +2);//delete the second element
V.erase (V.begin (), V.end ());//Delete all elements
return 0;
}
(8) Reversal of elements
Reverse () Method: Header file is #include<algorithm>
Reverse (V.begin (), V.end ());
(9) Ordering of elements
Sort () Method: Header File #include<algorithm>
The default method is ascending
You can customize the sorting method:
BOOL CMP (const int &AMP;A,CONST int &b)
{
Return a>b;
}
Sort (V.begin (), V.end (), CMP);
(10) The size of the vector
The size () method and the Empty () method
V.size () and V.empty ().

/************************************************************************************************/
Introduction to the String container:
(1) Creating a String Object
String s;//Initial initial length of 0
(2) Assigning a value to a string object
Law 1:s= "SJDJFJ";
FA 2:char ss[20];
scanf ("%s", SS);
S=ss;
(3) Adding a character to the tail of a string object
S=s+ ' a ';
(4) Adding a string to the tail of a string object
Law 1:s=s+ "ABC";
Law 2:s.append ("abc");
(5) String Object Insert character
String::iterator It=s.begin ();
S.insert (it+1, ' a ');
(6) Accessing a String object element
S= "ACFFGGG";
cout<<s[0];
(7) Deleting elements of a String object
1. Empty string can be directly assigned null string;
2. Use the Erase () method to delete the element that the iterator refers to or all the elements of that interval;
String s= "AAAAFFGGG";
String::iterator It=s.begin ();
S.erase (it+1);
S.erase (IT+1,IT+4);
(8) Returns the length of the string object and determines whether it is empty
S.length () and S.empty ();
(9) Replace the characters in string
S.replace (3,3, "gppg");//replace consecutive 3 characters with "GPPG" starting with the third character
(10) Searching for elements or substrings of a string object
Use the Find () method: Find a character with single quote ' ' definition; find a string delimited by double quotation marks "".
S.find (' C ');
S.find ("SDD");
(one) Comparison of String objects
A string object can be compared with other strings using the Compare () method, and returns 1 if it is larger than the other, or 1 if it is smaller than the other;
Returns 0 if it is the same as the other.
S.compare ("Ssfgg");
(12) Reverse Sort string Object
Reverse () Method: Header File #include<algorithm>
Reverse (S.begin (), S.end ());
String object as a vector element
vector<string>v;
V.push_back ("Jack");
V.push_back ("SHFJ");
cout<<v[0]<<v[1]<<endl;
cout<<v[0][0]<<endl;
Cout<<v[0].length () <<endl;

() String object interop with character array
Char ss[100];
scanf ("%s", ss);
S=ss;
printf (S.c_str ());
Cout<<endl;
printf ("%s", SS);
() string object and sscanf function
string s1,s2,s3
Char sa[100],sb[100],sc[100];
sscanf ("ABC 123 PC", "%s%s%s", SA, SB,SC);
S1=sa;
S2=SB;
S3=sc;
cout<<s1<< ' <<s2<< ' <<s3<<endl;
int a,b,c;
sscanf ("1 2 3", "%d%d%d", &a,&b,&c);
cout<<a<< ' <<b<< ' <<c<<endl;
int x, y, Z;
sscanf ("4,5$6", "%d,%d$%d", &x,&y,&z);
cout<<x<< ' <<y<< ' <<z<<endl;
(+) string object and value convert
#include <iostream>
#include <vector>
#include <sstream>
# Include<string>
using namespace std;

String converttostring (Double x)
{
Ostringstream o;
if (o<<x) return o.str ();//The variable x is read into the character stream o
return "error";
}

Double convertfromstring (const string &s)
{
Istringstream I (s);
Double X;
if (i>>x) return x;//is equivalent to reading a string from a character stream into the variable x
return 0.0;
}
int main ()
{
Char b[10];
String A;
sprintf (b, "%d", 1975);
A=b;
cout<<a<<endl;
String Cc=converttostring (1976);
cout<<cc<<endl;
String dd= "2006";
int p=convertfromstring (DD) +2;
cout<<p<<endl;
return 0;
}

/***************************************************************************************************/
Set Set container (red black tree principle)
(1) Creating a Set Collection Object
set<int>s;
(2) Insertion and middle order traversal of elements, reverse traversal (using forward iterators)
#include <set>
#include <iostream>
using namespace Std;
int main ()
{
set<int>s;
S.insert (8);
S.insert (1);
S.insert (12);
S.insert (6);
S.insert (8);//Repeat, do not insert operation
Set<int>::iterator it;
For (It=s.begin (); It!=s.end (); it++)//forward traversal
cout<<*it<<endl;
Set<int>::reverse_iterator rit;//Reverse Traversal
For (Rit=s.rbegin (); Rit!=s.rend (); rit++)
{
cout<<*rit<<endl;
}
return 0;
}
(3) Deletion of elements
#include <set>
#include <iostream>
using namespace Std;
int main ()
{
set<int>s;
S.insert (8);
S.insert (1);
S.insert (12);
S.insert (6);
S.insert (8);//Repeat, do not insert operation
S.erase (6);//delete element 6 (key value)
Set<int>::reverse_iteerator RIT;
For (Rit=s.rbegin (); Rit!=s.rend (); rit++)
cout<<*rit<<endl;
Cout<<s.size () <<endl;
return 0;
}
(4) Retrieval of elements
Search using the Find () method to return the position of the key value in the iterator later, or return a position after the last element, that is, end ().
Set<int>::iterator it;
It=s.find (6);
if (It!=s.end ()) cout<<*it<<endl;
(5) Custom comparison function
Case 1:
#include <set>
#include <iostream>
using namespace Std;
struct MYCOMP
{
BOOL Operator () (const int &AMP;A,CONST int &b)
{
Return a>b;
}
};
int main ()
{
set<int,mycomp>s;
S.insert (3);
S.insert (7);
S.insert (11);
S.insert (12);
Set<int,mycomp>::iterator it;
For (It=s.begin (); It!=s.end (); it++)
{
cout<<*it<<endl;
}
return 0;
}
Case 2:
#include <set>
#include <iostream>
using namespace Std;
struct INFO
{
String name;
Float score;
BOOL operator< (const info &a) const
{
Return a.score<score;
}
};
int main ()
{
set<info>s;
Info ifo;
Ifo.name= "DD";
ifo.score=999;
S.insert (IFO);
Ifo.name= "SS";
ifo.score=799;
S.insert (IFO);
Set<info>::iterator it;
For (It=s.begin (); It!=s.end (); it++)
cout<<*it<<endl;
return 0;
}
Multiset Multi-collection container (the red-black tree principle of repeatable elements)
(1) insertion of the Multiset element (the header file remains #include<set>)
#include <set>
#include <string>
#include <iostream>
using namespace Std;
int main ()
{
multiset<string>s;
S.insert ("Aad");
S.insert ("BBC");
Multiset<string>::iterator it;
For (It=s.begin (); It!=s.end (); it++)
cout<<*it<<endl;
return 0;
}
(2) Deletion of multiset elements
The erase () method allows you to delete an element in an iterator position in a Multiset object, an element in an iterator interval, a key value equal to all repeating elements of a value, and returns the number of deleted elements. Use the Clear () method to empty the element.
#include <set>
#include <string>
#include <iostream>
using namespace Std;
int main ()
{
multiset<string>s;
S.insert ("SSJJ");
S.insert ("SSJJ");
S.insert ("Dggh");
Multiset<string>::iterator it;
int N=s.erase ("SSJJ");
For (It=s.begin (); It!=s.end (); it++)
cout<<*it<<endl;
return 0;
}
(3) Finding elements
The Find method finds the element if found, returns the iterator position of the element (if the element repeats, returns the iterator position of the first repeating element), or returns the end () iterator position if it is not found.
#include <set>
#include <string>
#include <iostream>
using namespace Std;
int main ()
{
multiset<string>s;
S.insert ("abc");
S.insert ("Def");
S.insert ("HGJJ");
Multiset<string>::iterator it;
It=ms.find ("abc");
if (It!=s.end ())
cout<<*it<<endl;
return 0;
}

/******************************************************************************************/
Introduction to map Containers
The data structure of the map container is implemented by a red-black tree, the key value of the inserted element is not allowed to change, and the comparison function only compares the key values of the elements.

(1) Creating a Map object
The key value and the type of the mapping data are defined by themselves.
#include <map>
#include <iostream>
#include <string>
using namespace Std;
int main ()
{
map<string,float>m;
m["Jack"]=98.5;
m["Bomi"]=96;
m["Kagr"]=67;
Map<string,float>::iterator it;
For (It=m.begin (); It!=m.end (); it++)
cout<< (*it) .first<< ' << (*it) .second<<endl;
return 0;
}
(2) Deleting an element
Using the erase () function, you can delete an element, an element, and a repeating element of a key value.
#include <iostream>
#include <string>
#include <map>
int main ()
{
map<int,char>s;
S[1]= ' a ';
s[20]= ' t ';
s[15]= ' V ';
S.erase (20);
Map<int,char>::iterator it;
For (It=s.begin (); It!=s.end (); it++)
cout<< (*it) .second<<endl;
return 0;
}
(3) Reverse traversal of elements
Use the iterator reverse_iterator the reverse traversal and the rbegin (), rend () method to traverse.
#include <map>
#include <string>
#include <iostream>
using namespace Std;
int main ()
{
map<int,char>s;
S[1]= ' a ';
S[2]= ' B ';
S[20]= ' F ';
Map<int,char>::reverse_iterator RIT;
For (Rit=s.rbegin (); Rit!=s.rend (); rit++)
cout<< (*rit) .first<< ' << (*rit) .second<<endl;
return 0;
}
(4) Searching for elements
Use the Find () method to search for a key value, search for the location of the iterator where it will be returned, or return the end () iterator position.
Act 1:
#include <map>
#include <string>
#include <iostream>
using namespace Std;
int main ()
{
map<int,char>s;
S[1]= ' a ';
S[2]= ' B ';
S[20]= ' F ';
Map<int,char>::iterator it;
It=s.find (2);
if (it! =s.end ())
cout<< (*it) .first<< ' << (*it) .second<<endl;
return 0;
}
(5) Custom comparison function
The default function sort is to insert elements in order of key values from small to large
#include <iostream>
#include <string>
#include <map>
using namespace Std;
struct MYCOMP
{
BOOL Operator () (const int &AMP;A,CONST int &b)
{
Return a>b;
}
};
int main ()
{
map<int,char,mycomp>m;
m[25]= ' m ';
M[28]= ' F ';
M[10]= ' a ';
Map<int,char,mycomp>::iterator it;
For (It=m.begin (); It!=m.end (); it++)
{
cout<< (*it) .first<< ' << (*it) .second<<endl;
}
return 0;
}
Act 2:
#include <iostream>
#include <string>
#include <map>
using namespace Std;
struct INFO
{
String name;
Float score;
BOOL operator< (const info &a) const
{
Return a.score<score;
}
};
int main ()
{
map<info,int>m;
Info ifo;
Ifo.name= "SDJ";
ifo.score=80;
m[ifo]=25;
Map<info,int>::iterator it;
For (It=m.begin (); It!=m.end (); it++)
{
cout<< (*it). Second;
cout<< (*it) .name<< "<< ((*it). First) .score<<endl;
}
return 0;
}
Application:
1.map Container for digital separation
#include <string>
#include <map>
#include <iostream>
int main ()
{
map<char,int>m;
for (int i=0;i<10;i++)
{
m[' 0 ' +j]=j;
}
String sa;
Sa= "ASDDDDD";
int sum=0;
for (int i=0;i<sa.length (); i++)
Sum+=m[sa[i]];
cout<<sum<<endl;
return 0;
}
2.map container for digital print characters
#include <iostream>
#include <map>
#include <string>
int main ()
{
map<int,char>m;
for (int i=0;i<10;i++)
m[j]= ' 0 ' +j;
String A= "The number is:";
cout<<s+m[7]<<endl;
return 0;
}


/******************************************************************************************************/
Multimap Container Introduction
(1) insertion of elements
#include <iostream>
#include <map>
#include <string>
using namespace Std;
Int main ()
{
mmultimap<string,double>m;
M.insert (Pair<string,double> ("Jack", 300.5));
M.insert (pair<string,double> ("LAN", 5868));
M.insert (pair<string,double> ("HDHF", 6886));
Multimap<string,double>::iterator it;
for (It=m.begin (); It!=m.end (); it++)
cout<< (*it) .first<< ' << (*it). Second<<endl;
return 0;
}


(2) Deletion of elements
#include <iostream>
#include <map>
#include <string>
using namespace Std;
int main ()
{
multimap<string,double>m;
M.insert (pair<string,double> ("Jack", 300.6));
M.insert (pair<string,double> ("Jsjjd", 300.56));
M.insert (pair<string,double> ("DJJ", 384));
M.erase ("Jack");
Multimap<string,double>::iterator it;
For (It=m.begin (); It!=m.end (); it++)
cout<< (*it) .first<< ' << (*it) .second<<endl;
return 0;
}
(3) Searching for elements
With the Find () method, returns the subscript for the first key value if found, otherwise the end () iterator position is returned.


/******************************************************************************************/
List doubly linked list container
List each node has three fields: Precursor element pointer field, data field, successor element pointer field
The iterator can be moved to the successor/predecessor node only through the operation "+ +" or "--" and cannot perform the operation "+n" or "-n";
(1) Creating a list Object
1. Create an empty list:list<int>m;
2. Create a linked list with n elements: list<int>m (10);
(2) Insertion and traversal of elements
The Push_back (), Push_front (), and insert () methods are used.
#include <list>
#include <iostream>
using namespace Std;
int main ()
{
list<int>m;
M.push_back (2);
M.push_back (6);
M.push_front (9);
List<int>::iterator it;
it++;
M.insert (it,20);
For (It=m.begin (); It!=m.end (); it++)
cout<< (*it) <<endl;
return 0;
}
(3) Reverse traversal
Reverse traversal with reverse iterator reverse_iterator plus rbegin (), rend () method
(4) Element deletion
1. Use the Remove () method to delete an element in the linked list that has the same element value will be deleted;
2. Use the Pop_front () and Pop_back () methods to remove the kinsoku elements;
3. Use the Erase () method to remove elements from the position of the iterator;
List<int>::iterator it;
It=s.begin ();
it++;
S.erase (IT);
4. Use the Clear () method to clear the list
(4) Element lookup
Use the Find () method to find:
List<int>::iterator it;
It=find (L.begin (), L.end (), 7);
if (It!=l.end ())
cout<<*it<<endl;
(5) Ordering of elements
Use the sort () method
(6) Elimination of continuous repeating elements
Use the unique () method

/**************************************************************************************/
Priority_queue Priority Queue Container
Push (): Insert Element
Pop (): delete element
Top (): Read the first element of the team
Empty (): blank
Size (): number of Read elements
Overloading < operator definition Precedence
struct INFO
{
String name;
Float score;
BOOL operator< (const Info &a) const
{
Return a.score<score;
}
};
priority_queue<info>q;

Overload "()" operator defines precedence
struct MYCOMP
{
BOOL Operator () (const int &a,int &b)
{
Return a>b;//here is the opposite of the other containers,> means,< from small to large to arrange from large to smaller
}
};

C++STL basic knowledge of generic programming explained--------February 3, 2015

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.