Notes on common usage of vector, MAP, set, sort, and list in STL

Source: Internet
Author: User

Original post address: http://hi.baidu.com/yanfei_1/blog/item/a0a538331f5256f91a4cffba.html

C ++'s standard template library (STL) is a class library for containers and algorithms. Containers often contain the same type of data. The most common containers in STL are vector, set, and map. common algorithms include sort.
.
1. Vector
1. Statement:
A vector is similar to a dynamic one-dimensional array.
Vector <int> A; // declare a vector A whose element is of the int type.
Vectot <mytype> A; // declare a vector A whose element is of the mytype type.
Here, the declared a contains 0 elements, that is, the value of A. Size () is 0, but it is dynamic, and its size will follow the data insertion.

And delete changes.
Vector <int> A (100, 0); // here, we declare an integer vector that has already stored 100 zeros.
2. vector operations
Common functions:
Size_t size (); // returns the vector size, that is, the number of included elements
Void pop_back (); // deletes the element at the end of the vector. The vector size is reduced by one.
Void push_back (); // used to add elements to the end of a vector
T back (); // returns the element at the end of the vector.
Void clear (); // clears the vector and changes the vector size to 0.
Other access methods:
Cout <A [5] <Endl;
Cout <A. At (5) <Endl;
The above difference is that the latter will throw an exception during access across the border, but the former will not.
Example:
Int intarray [10];
Vector <int> first_vector (intarray, intarray + 10 );
Vector <int> second_vector (first_vector.begin (), first_vector.end ());
Class man
{
Public:
Ansistirng ID;
Ansistring MC;
}
Vector <man> manlist;
Man thisman;
Thisman. ID = "2001 ";
Thisman. Name = "yourname ";
Manlist. push_back thisman; // Add the first element.
Thisman. ID = "2002 ";
Thisman. Name = "myname ";
Manlist. push_back thisman; // Add the second element.

Manlist. Clear (); // clear
3. Traverse
(1). For (vector <datatype>: iterator it = A. Begin (); it! = A. End (); It ++)
Cout <* It <Endl;
(2). For (INT I = 0; I <A. size; I ++)
Cout <A [I] <Endl;
Ii. Map
Map is an associated container of STL, which provides one-to-one (the first can be called a keyword, each keyword can only appear once in map, and the second can be called the value of this keyword) because of this feature
The internal implementation of map is to build a red-black tree (a non-strictly balanced binary tree), which has the ability to automatically sort data.
The following is an example of one-to-one data ing. For example, in a class, each student's student ID has a one-to-one ing relationship with his/her name. This model may be easily described using map,
Obviously, the student ID is described by INT and the name is described by string (in this article, char * is not used to describe the string, but string in STL is used to describe it ),
The following is the map description code:

1. Declaration method:
Map <int, string> mapstudent;
2. Data insertion
After constructing the map container, We can insert data into it. Here are three data insertion methods:
First: insert pair data using the insert Function
Map <int, string> mapstudent;
Mapstudent. insert (pair <int, string> (1, "student_one "));
Type 2: insert value_type data using the insert Function
Map <int, string> mapstudent;
Mapstudent. insert (Map <int, string>: value_type (1, "student_one "));
Third: insert data using Arrays
Map <int, string> mapstudent;
Mapstudent [1] = "student_one ";
Mapstudent [2] = "student_two ";
3. Map size
How do we know how much data has been inserted into the map? We can use the size function:
Int nsize = mapstudent. Size ();
4. Data Traversal
First: Apply the forward iterator
Map <int, string >:: iterator ITER;
For (iter = mapstudent. Begin (); iter! = Mapstudent. End (); ITER ++)
Cout <ITER-> first <"<ITER-> second <end;
Type 2: Apply the reversed-phase iterator
Map <int, string >:: reverse_iterator ITER;
For (iter = mapstudent. rbegin (); iter! = Mapstudent. rend (); ITER ++)
Cout <ITER-> first <"<ITER-> second <end;
Method 3: Array
Int nsize = mapstudent. Size ()
For (INT nindex = 1; nindex <= nsize; nindex ++)
Cout <mapstudent [nindex] <end;
5. Search for data (including determining whether the keyword appears in map)
Three data search methods are provided here.
First: Use the count function to determine whether a keyword exists, but cannot locate the data location.
Type 2: Use the find function to locate the data occurrence location. It returns an iterator,
When the data appears, it returns the iterator where the data is located. If there is no data to be searched in the map, the iterator it returns is equal to the iterator returned by the end function.
Int main ()
{
Map <int, string> mapstudent;
Mapstudent. insert (pair <int, string> (1, "student_one "));
Mapstudent. insert (pair <int, string> (2, "student_two "));
Mapstudent. insert (pair <int, string> (3, "student_three "));
Map <int, string >:: iterator ITER;
Iter = mapstudent. Find (1 );
If (ITER! = Mapstudent. End ())
{
Cout <"find, the value is" <ITER-> second <Endl;
}
Else
{
Cout <"do not find" <Endl;
}
}
Method 3: This method is used to determine whether data exists.
Lower_bound function usage. This function is used to return the lower bound of the keyword to be searched (an iterator)
Upper_bound function usage. This function is used to return the upper bound of the keyword to be searched (an iterator)
For example, if the values of 1, 2, 3, and 4 have been inserted in the map, if lower_bound (2) is used, 2 is returned, and if the value of upper-bound (2) is used, 3 is returned.
The pai_range function returns a pair. The first variable in pair is the iterator returned by lower_bound. The second iterator in pair is the iterator returned by upper_bound. If the two iterators are equal, this keyword is not displayed in map.
Mappair = mapstudent. interval _range (2 );
If (mappair. First = mappair. Second)

Cout <"do not find" <Endl;
6. Empty and empty data
The clear () function can be used to clear the data in the map to determine whether there is data in the map. The empty () function can be used. If it returns true, it indicates that the map is empty.
7. data deletion
Here the erase function is used. It has three overloaded functions.
Iterator Deletion
Iter = mapstudent. Find (1 );
Mapstudent. Erase (ITER );
Delete with keywords
Int n = mapstudent. Erase (1); // If deleted, 1 is returned; otherwise, 0 is returned.
Use an iterator to delete parts
The Code clears the entire map.
Mapstudent. earse (mapstudent. Begin (), mapstudent. End ());
// When you delete a part, it is also a STL feature. The delete interval is a set of pre-closed and post-open.
8. Other functions
Swap, key_comp, value_comp, get_allocator, and other functions are provided here. If you are interested, you can study them yourself.

Iii. Set
Set is a set and does not contain repeated elements, which is different from vector.
Definition:
Defines a set of integers. You can use
Set <int>;
Basic operations:
For elements in set
Insert element: a. insert (1 );
Delete an element (if any): A. Erase (1 );
Determine whether an element belongs to a set: If (A. Find (1 )! = A. End ())...
Returns the number of elements in the Set: A. Size ()
Empty set: A. Clear ()
Union, intersection, and difference of a set
Set_union (. begin (),. end (), B. begin (), B. end (), insert_iterator <set <int> (C, C. begin ()));
Set_intersection (. begin (),. end (), B. begin (), B. end (), insert_iterator <set <int> (C, C. begin ()));
Set_difference (. begin (),. end (), B. begin (), B. end (), insert_iterator <set <int> (C, C. begin ()));
(Note that C should be empty before this ).
Note:
It is very important that, in order to achieve quick operation of the Set, the implementation of the Set adopts a balanced binary tree. Therefore, the elements in the set must be sortable. If it is a custom type, the operator <must be defined while defining the type.
Iv. Sort
As the name implies, sort is sorting.
Usage:
Single Keyword:
For vector
Sort (& A [0], & A [n]); // n = A. Size () sorts the elements in a progressively.
Multiple keywords:
We can also use the pair class
Vector <pair <int, int> A; // note the two >>> there must be a space in the middle; otherwise, the compiler considers it an operator>
For example:
Int n, x, y;
Cin> N;
For (INT I = 0; I <n; ++ I ){
Cin> x> Y;
A. push_back (make_pair (x, y); // make_pair is used to create a pair object.
}
Sort (& A [0], & A [n]);
Note:
For the classes or structures defined by ourselves, the system generally cannot compare operations for me. We need to define the corresponding operators by ourselves. <
Bool operator <(const mytype & X, const mytype & Y)
{
// Return true if x <Y, false if x> = y
}

List is a list

# Include <list>

Using namespace STD;
Typedef list <stuserlistnode *> userlist; // stores user information

Add

Clientlist. push_back (currentuser );

Delete

Clientlist. Remove (* removeiterator );

Search

Stuserlistnode getuser (char * username) // obtain user information based on the user name
{
For (userlist: iterator useriterator = clientlist. Begin ();
Useriterator! = Clientlist. End ();
++ Useriterator)
{
If (strcmp (* useriterator)-> username), username) = 0)
Return * (* useriterator );
}
Throw exception ("not find this user ");
}

 

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.