Common usage of vector, MAP, set, and sort in STL

Source: Internet
Author: User

C ++'s standard template library (STL) is a container andAlgorithmClass Library. 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 A; // declare a vector A whose element is of the int type.
Vectot 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 A (100, 0); // The declared here is an integer vector that stores 100 0.

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:
The difference between cout <and above is that the latter throws an exception when the access is out of bounds, but the former does not.

Example:
Int intarray [10];
Vector first_vector (intarray, intarray + 10 );
Vector second_vector (first_vector.begin (), first_vector.end ());
Class man
{
Public:
Ansistirng ID;
Ansistring MC;
}
Vector 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: iterator it = A. Begin (); it! = A. End (); It ++)

Cout <* It <

(2). For (INT I = 0; I

Cout <

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 in int and the name is described in string.ArticleDoes not use char * to describe the string, but uses string in STL ),
The following is a map description.Code:

1. Declaration method:
Map 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 mapstudent;
Mapstudent. insert (pair (1, "student_one "));

Type 2: insert value_type data using the insert Function
Map mapstudent;
Mapstudent. insert (MAP: value_type (1, "student_one "));
Third: insert data using Arrays

Map 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: iterator ITER;
For (iter = mapstudent. Begin (); iter! = Mapstudent. End (); ITER ++)
Cout <first <"<second type: Apply the reversed-phase iterator
Map: reverse_iterator ITER;
For (iter = mapstudent. rbegin (); iter! = Mapstudent. rend (); ITER ++)
Cout <first <"<second <3: Using Arrays
Int nsize = mapstudent. Size ()
For (INT nindex = 1; nindex <= nsize; nindex ++)
Cout <5. Search for data (including checking 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 mapstudent;
Mapstudent. insert (pair (1, "student_one "));
Mapstudent. insert (pair (2, "student_two "));
Mapstudent. insert (pair (3, "student_three "));
Map: iterator ITER;
Iter = mapstudent. Find (1 );
If (ITER! = Mapstudent. End ())
{
Cout <"find, the value is" <second <}
Else
{
Cout <"do not find" <}
}
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 does not appear in the map, Program Description
Mappair = mapstudent. interval _range (2 );
If (mappair. First = mappair. Second)
Cout <"do not find" <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;

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 (A. Begin (), A. End (), B. Begin (), B. End (), insert_iterator> (C, C. Begin ()));
Set_intersection (A. Begin (), A. End (), B. Begin (), B. End (), insert_iterator> (C, C. Begin ()));
Set_difference (A. Begin (), A. End (), B. Begin (), B. End (), insert_iterator> (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.

4. sort
sort is sorting
usage:
single keyword:
for vector A
sort (& A [0], & A [n]); // n =. size () sorts the elements in a progressively.
multiple keywords:
we can also use the pair class
vector A; // note the two here> there must be a space in the middle, otherwise, the compiler determines the operator >>< br> example:
int n, x, y;

Cin> N;
For (INT I = 0; 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
}

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.