STL Set,map

Source: Internet
Author: User
Tags visual studio 2010

I. Set and Multiset
Set, Multiset, map, Multimap
The inner elements are arranged in an orderly manner, and the position of the new element is determined by its value, which is faster.
In addition to the functions that each container has, the following member functions are supported:
Find: Finds an element equal to a value (x less than Y and y less than x is not immediately equal)
Lower_bound: Finding a lower bound
Upper_bound: Finding an upper bound
Equal_range: Finding both upper and lower bounds
Count: Calculates the number of elements equal to a value (x is less than Y and y is less than x and is not immediately equal)
Insert: For inserting an element or an interval

Pre-knowledge: pair Template

1template<class_T1,class_t2>2 structpair3 {4 typedef _t1 First_type;5 typedef _t2 Second_type;6 _t1 first;7 _t2 second;8 pair (): First (), second () {}9PairConst_t1& __a,Const_t2&__b)Ten : First (__a), second (__b) {} Onetemplate<class_U1,class_u2> APairConstPAIR&LT;_U1, _u2>&__p) - : First (__p.first), second (__p.second) {} -};


The Map/multimap container is the object of the pair template class, and is sorted by first from small to large
A third constructor usage example:
pair<int,int>
p (pair<double,double> (5.5,4.6));
//P.first = 5, P.second = 4
5
Multiset
Template<class Key, class Pred = Less<key>,
Class A = allocator<key> >
Class Multiset {...};
? Variables of the pred type determine the elements in the multiset, "one is smaller than the other" is how to define.
Multiset the process of running, comparing the size of two elements x, Y, is to generate a pred type of
variable, which is assumed to be op, if the expression op (x, y) return value is true, X is smaller than Y.
The default type of pred is less<key>.
6
Multiset
Template<class Key, class Pred = Less<key>,
Class A = allocator<key> >
Class Multiset {...};
? Variables of the pred type determine the elements in the multiset, "one is smaller than the other" is how to define.
Multiset the process of running, comparing the size of two elements x, Y, is to generate a pred type of
variable, which is assumed to be op, if the expression op (x, y) return value is true, X is smaller than Y.
The default type of pred is less<key>.
? Definition of less Template:
Template<class t>
struct Less:public binary_function<t, T, bool>
{bool operator () (const t& x, const t& y) {return x < y;} const;};
Less templates are sized by <
7
MultisetThe member function
Iterator Find (const T & val);
Finds an element with a value of Val in the container and returns its iterator. If not found, returns end ().
Iterator Insert (const T & val); Inserts Val into the container and returns its iterator.
void Insert (iterator first,iterator last); Insert the interval [first,last] into the container.
int count (const T & val); Counts how many elements have the same value as Val.
Iterator Lower_bound (const T & val);
Find one of the largest locations in it so that [begin (), it) all the elements are smaller than Val.
Iterator Upper_bound (const T & val);
Find a minimum position of it so that all elements in [It,end ()) are larger than Val.
8
MultisetThe member function
Pair<iterator,iterator> equal_range (const T & val);
Lower_bound and Upper_bound are also obtained.
Iterator Erase (iterator it);
Removes an iterator to the element that it points to, returning the elements behind it (this is true on Visual studio 2010, but
In the C + + standard and dev C + +, this is not the return value.
9
The use of Multiset
#include <set>
using namespace Std;
Class A {};
int main () {
Multiset<a> A;
A.insert (A ()); Error
}
Ten
The use of Multiset
#include <set>
using namespace Std;
Class A {};
int main () {
Multiset<a> A;
A.insert (A ()); Error
}
Multiset <A> A;
is equivalent to
Multiset<a, less<a>> A;
When an element is inserted, Multiset will be inserted into the element and the
There are elements to compare. Since the less template is used in <
Comparisons, so that all require a's object to be able to use < ratio
More, that is, proper overloading of <
One
Example of multiset usage
#include <iostream>
#include <set>//Use of Multiset must include this file
using namespace Std;
Template <class t>
void Print (t first, t last)
{for (; first! = last; ++first) cout << * First << "";
cout << Endl;
}
Class A {
Private
int n;
Public
A (int n_) {n = n_;}
friend BOOL operator< (const A & A1, const A & A2) {return A1.N < A2.N;}
Friend Ostream & operator<< (Ostream & O, const A & A2) {o << a2.n; return o;}
Friend class Myless;
};
A
struct Myless {
BOOL Operator () (const A & A1, const A & A2)
By single digit ratio size
{return (A1.N) < (a2.n% 10);}
};
typedef multiset<a> MSET1; MSET1 with "<" compare size
typedef multiset<a,myless> MSET2; MSET2 with Myless::operator () compare size
int main ()
{
const int SIZE = 6;
A A[size] = {4,22,19,8,33,40};
MSET1 M1;
M1.insert (a,a+size);
M1.insert (22);
cout << "1)" << m1.count << Endl; Output 1) 2
cout << "2)"; Print (M1.begin (), M1.end ()); Output 2) 4 8 19 22 22 33 40
-
M1 elements: 4 8 19 22 22 33 40
Mset1::iterator pp = m1.find (19);
if (pp! = M1.end ())/condition for true description found
cout << "found" << Endl;
The bank will be executed, output found
cout << "3)"; cout << * M1.lower_bound (+) << ","
<<* M1.upper_bound ($) << Endl;
Output 3) 22,33
pp = M1.erase (m1.lower_bound), M1.upper_bound (22));
PP points to the next element of the deleted element
cout << "4)"; Print (M1.begin (), M1.end ()); Output 4) 4 8 19 33 40
cout << "5)"; cout << * pp << Endl; Output 5) 33
MSET2 m2; The elements in the M2 are small to large by the number of bits in N.
M2.insert (a,a+size);
cout << "6)"; Print (M2.begin (), M2.end ()); Output 6) 40 22 33 4 8 19
return 0;
}
-
M1 elements: 4 8 19 22 22 33 40
Mset1::iterator pp = m1.find (19);
if (pp! = M1.end ())/condition for true description found
cout << "found" << Endl;
The bank will be executed, output found
cout << "3)"; cout << * M1.lower_bound (+) << ","
<<* M1.upper_bound ($) << Endl;
Output 3) 22,33
pp = M1.erase (m1.lower_bound), M1.upper_bound (22));
PP points to the next element of the deleted element
cout << "4)"; Print (M1.begin (), M1.end ()); Output 4) 4 8 19 33 40
cout << "5)"; cout << * pp << Endl; Output 5) 33
MSET2 m2; The elements in the M2 are small to large by the number of bits in N.
M2.insert (a,a+size);
cout << "6)"; Print (M2.begin (), M2.end ()); Output 6) 40 22 33 4 8 19
return 0;
} iterator Lower_bound (const T & val);
Find one of the largest locations in it so that [begin (), it) all the elements are smaller than Val.
the
Output:
1) 2
2) 4 8 19 22 22 33 40
3) 22,33
4) 4 8 19 33 40
5) 33
6) 40 22 33 4 8 19
-
Set
Template<class Key, class Pred = Less<key>,
Class A = allocator<key> >
Class set {...}
When inserting an existing element in a set, the insertion is ignored.
-
#include <iostream>
#include <set>
using namespace Std;
int main () {
typedef set<int>::iterator IT;
int a[5] = {3,4,6,1,2};
Set<int> St (a,a+5); St-Li is 1 2 3 4 6
pair< it,bool> result;
result = St.insert (5); St becomes 1 2 3 4 5 6
if (result.second)//Insert succeeds then output is inserted element
cout << * Result.first << "inserted" << Endl; Output: 5 inserted
if (St.insert (5). Second) cout << * Result.first << Endl;
Else
cout << * Result.first << "already exists" << Endl; Output 5 already exists
pair<it,it> bounds = St.equal_range (4);
cout << * Bounds.first << "," << * bounds.second; Output: 4,5
return 0;
}
Set Usage Example
Output Result:
5 Inserted
5 already exists
4,5
-
In-video Quiz
1. Which of the following object definition statements is wrong?
A) pair<int,int> a (3.4,5.5);
b) pair<string,int> B;
C) pair<string,int> K (pair<char*,double> ("This", 4.5));
D) pair<string,int> x (pair<double,int> B (3.4,100));
2. What operators do I need to overload to allow the following program to compile?
Class A {};
multiset<a,greater<a> > B;
B.insert (A ());
A) = = B) = C) > D) <
+
In-video Quiz
1. Which of the following object definition statements is wrong?
A) pair<int,int> a (3.4,5.5);
b) pair<string,int> B;
C) pair<string,int> K (pair<char*,double> ("This", 4.5));
D) pair<string,int> x (pair<double,int> B (3.4,100));
2. What operators do I need to overload to allow the following program to compile?
Class A {};
multiset<a,greater<a> > B;
B.insert (A ());
A) = = B) = C) > D) <
-
In-video Quiz
3. The following program fragment outputs the result:
int a[] = {2,3,4,5,7,3};
Multiset<int> MP (A,A+6);
cout << * Mp.lower_bound (4);
A) 2 B) 3 C) 4 D) 5
4. The return value type of the Equal_range member function of the Set<double> class is:
A) void
B) Pair<set<double>::iterator, set<double>::iterator>
C) pair<int,int>
D) pair<set<double>::iterator,bool>

Program Design Internship
Guo Wei Weibo Http://weibo.com/guoweiofpku
http://blog.sina.com.cn/u/3266490431
Liu Jia Ying Weibo http://weibo.com/pkuliujiaying
School of Information Science and technology
1
Standard Template Library STL
Map and Multimap
School of Information Science and Technology "program design Practice" Guo Wei Liu Jia Ying
2
3
Pre-knowledge: pair Template
Template<class _t1, Class _t2>
struct pair
{
typedef _T1 FIRST_TYPE;
typedef _T2 SECOND_TYPE;
_T1 first;
_t2 second;
Pair (): First (), second () {}
Pair (const _t1& __a, const _t2& __b)
: First (__a), second (__b) {}
Template<class _U1, Class _u2>
Pair (const PAIR&LT;_U1, _u2>& __p)
: First (__p.first), second (__p.second) {}
};
The Map/multimap are all in the pair mode.
Class, and by first from small to large rows
Order
A third constructor usage example:
Pair<int,int>
P (pair<double,double> (5.5,4.6));
P.first = 5, P.second = 4
4
Multimap
Template<class Key, Class T, class Pred = Less<key>
Class A = allocator<t> >
Class Multimap {
....
typedef pair<const Key, t> value_type;
.......
}; Key represents the type of the keyword
? The elements in Multimap are composed of < keywords, value >, each element is a pair object, the keyword
is the first member variable, and its type is key
? The keywords in multimap allow multiple elements to be the same. Elements are small to large according to first member variables
The "less than" relationship of the keyword is defined by default with less<key>.
5
#include <iostream>
#include <map>
using namespace Std;
int main () {
typedef multimap<int,double,less<int> > Mmid;
Mmid pairs;
cout << "1" << pairs.count << Endl;
Pairs.insert (Mmid::value_type (15,2.7));//typedef pair<const Key, t> value_type;
Pairs.insert (Mmid::value_type (15,99.3));
cout << "2" << pairs.count << Endl; The number of elements that the keyword equals a value
Pairs.insert (Mmid::value_type (30,111.11));
Pairs.insert (Mmid::value_type (10,22.22));
Output:
1) 0
2) 2
Multimap Example
6
Pairs.insert (Mmid::value_type (25,33.333));
Pairs.insert (Mmid::value_type (20,9.3));
for (Mmid::const_iterator i = Pairs.begin ();
I! = Pairs.end (); i + +)
cout << "(" << i->first << "," << i->second << ")" << ",";
}
Output:
1) 0
2) 2
(10,22.22), (15,2.7), (15,99.3), (20,9.3), (25,33.333), (30,111.11)
7
A student score entry and inquiry system,
Accept the following two types of inputs:
Add Name ID Score
Query Score
Name is a string with no spaces in the middle that represents the student's name. ID is an integer representing the school number
。 Score is an integer that represents a fraction. The number is not repeated, and the scores and names may be duplicated.
The two types of input alternately appear. The first input indicates the information to be added to a student, which
, write down the student's name, ID and score. The second input indicates that you want to query and hit this type of input
, the name, school number, and score of the highest score of the record in which the scores are lower than score are output. Such as
If more than one student satisfies the condition, the student's information is the largest of the output number. If you do not find the
Students satisfying the condition, the output "Nobody"
Multimap examples
8
Input Sample:
ADD Jack 12 78
Query 78
Query 81
ADD Percy 9 81
ADD Marry 8 81
Query 82
ADD Tom 11 79
Query 80
Query 81
Example of output fruit sample:
Nobody
Jack 12 78
Percy 9 81
Tom 11 79
Tom 11 79
9
#include <iostream>
#include <map>//use Multimap to include this header file
#include <string>
using namespace Std;
Class Cstudent
{
Public
struct Cinfo//class can also be defined within a class
{
int id;
String name;
};
int score;
Cinfo info; Additional Information for students
};
typedef multimap<int, cstudent::cinfo> MAP_STD;
Ten
int main () {
MAP_STD MP;
Cstudent St;
string cmd;
while (Cin >> cmd) {
if (cmd = = "Add") {
CIN >> st.info.name >> st.info.id >> st.score;
Mp.insert (Map_std::value_type (st.score,st.info));
}
else if (cmd = = "Query") {
int score;
CIN >> Score;
Map_std::iterator p = mp.lower_bound (score);
if (p!= mp.begin ()) {
--p;
Score = p->first; than the highest score to query for low scores
Map_std::iterator MAXP = p;
int MAXID = p->second.id;
One
int main () {
MAP_STD MP;
Cstudent St;
string cmd;
while (Cin >> cmd) {
if (cmd = = "Add") {
CIN >> st.info.name >> st.info.id >> st.score;
Mp.insert (Map_std::value_type (st.score,st.info));
}
else if (cmd = = "Query") {
int score;
CIN >> Score;
Map_std::iterator p = mp.lower_bound (score);
if (p!= mp.begin ()) {
--p;
Score = p->first; than the highest score to query for low scores
Map_std::iterator MAXP = p;
int MAXID = p->second.id;
Iterator Lower_bound
(const T & val);
Find one of the largest locations it makes
First of all elements in [begin (), it)
Are smaller than Val.
A
for (; P! = Mp.begin () && P->first = =
Score; --P) {
Traverse all grades and score equal students
if (P->second.id > Maxid) {
MAXP = p;
Maxid = p->second.id;
}
}
if (P->first = = score) {
If the above loop is because p = = Mp.begin ()
and terminated, the element that P points to is also processed
if (P->second.id > Maxid) {
MAXP = p;
Maxid = p->second.id;
}
}
-
cout << Maxp->second.name <<
"<< maxp->second.id <<" "
<< Maxp->first << Endl;
}
Else
The result of the lower_bound is the begin, stating that no one scores lower than the query score
cout << "Nobody" << Endl;
}
}
return 0;
}
-
cout << Maxp->second.name <<
"<< maxp->second.id <<" "
<< Maxp->first << Endl;
}
Else
The result of the lower_bound is the begin, stating that no one scores lower than the query score
cout << "Nobody" << Endl;
}
}
return 0;
}
Mp.insert (Map_std::value_type (st.score,st.info));
Mp.insert (Make_pair (st.score,st.info)); can also
the
Map
Template<class Key, Class T, class Pred = Less<key>
Class A = allocator<t> >
Class Map {
....
typedef pair<const Key, t> value_type;
.......
};
? The elements in the map are the pair template class objects. Keywords (first member variables) are different. Yuan
From small to large in accordance with the key words, by default with Less<key&gt, that is, "<" definition "small
To ".
-
If pairs is an object of the map template class,
Pairs[key]
Returns a reference to the value (second member variable) of the element that has the keyword equal to key. If there is no key
The element with the Word key will insert a key element into the pairs, whose value is used without a parameter
The constructor initializes and returns a reference to its value.
Map's [] member function
-
If pairs is an object of the map template class,
Pairs[key]
Returns a reference to the value (second member variable) of the element that has the keyword equal to key. If there is no key
The element with the Word key will insert a key element into the pairs, whose value is used without a parameter
The constructor initializes and returns a reference to its value.
Such as:
Map<int,double> pairs;
The
PAIRS[50] = 5; Modifies the element with the keyword 50 in pairs so that its value becomes 5.
If no element with the keyword equals 50 is present, the element is inserted and the value becomes 5.
Map's [] member function
-
#include <iostream>
#include <map>
using namespace Std;
Template <class Key,class value>
Ostream & operator << (Ostream & O, const pair<key,value> & P)
{
o << "(" << p.first << "," << p.second << ")";
return o;
}
Map example
+
int main () {
typedef map<int, double,less<int> > Mmid;
Mmid pairs;
cout << "1" << pairs.count << Endl;
Pairs.insert (Mmid::value_type (15,2.7));
Pairs.insert (Make_pair (15,99.3)); Make_pair generating a Pair object
cout << "2" << pairs.count << Endl;
Pairs.insert (Mmid::value_type (20,9.3));
Mmid::iterator i;
cout << "3)";
for (i = Pairs.begin (); I! = Pairs.end (); i + +)
cout << * I << ",";
cout << Endl;
Output:
1) 0
2) 1
3) (15,2.7), (20,9.3),
-
cout << "4)";
int n = pairs[40];//If there is no element with the keyword 40, insert a
for (i = Pairs.begin (); I! = Pairs.end (); i + +)
cout << * I << ",";
cout << Endl;
cout << "5)";
PAIRS[15] = 6.28; Change the element value of the keyword 15 to 6.28
for (i = Pairs.begin (); I! = Pairs.end (); i + +)
cout << * I << ",";
}
Output:
1) 0
2) 1
3) (15,2.7), (20,9.3),
4) (15,2.7), (20,9.3), (40,0),
5) (15,6.28), (20,9.3), (40,0),
+
1. Which of the following three programs does not cause compilation errors? (Hint, the subject is very pit)
A) Multimap <string,greater<string> > MP;
B) Multimap <string,double,less<int> > MP1; Mp1.insert (Make_pair ("OK", 3.14));
C) multimap<string,double> MP2; Mp2.insert ("OK", 3.14);
D) will cause compilation errors
2. Have the object Map<string,int> MP; The return value type of the expression mp["OK" is:
A) int B) int & C) string D) string &
In-video Quiz

STL Set,map

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.