C ++ object-oriented programming study notes (9)

pair map set

STL pair

Defined in (1) pair of

Header file <utility>
of STL Described in a header file looks very simple template class pair, to represent a binary or group of elements and provided on the element size in lexicographic order comparison operator performs the template function.

Defines a pair object represents a point of planar coordinates:
Example:

pair<double, double> p;
cin >> p.first >> p.second;

or

pair <string,double> product1 ("tomatoes",3.25);

pair template class requires two parameters: the data type of the first element and the tail element. pair template class object has two members: first and second, respectively first element and the last element.

Example:

pair<int,int>p1;
    pair<int,int>p2;
    cin>>p1.first>>p1.second;
    cin>>p2.first>>p2.second;
    cout<<'<'<<p1.first<<','<<p1.second<<'>'<<endl;
    cout<<'<'<<p2.first<<','<<p2.second<<'>'<<endl;

Output
<p1.first, p1.second>
<p2.first, p2.second>

Comparison (2) pair of

In <utility>the six comparison operators have been defined on the pair: <,>, <= ,> =, ==, =, it is the first of its rules than!
Than the first, first equal time and then compare the second, in line with most applications logic. Of course, these may be overloaded by the operator
to reassign ⼰ from the comparison logic.

Example:

 if(p1>p2) cout<<"p1"<<endl;
    else if(p2>p1) cout<<"p2"<<endl;
    else cout<<"equal"<<endl;

(3) pair is generated on the fly

In addition to directly define a pair objects, you need to instantly generate a pair if an object, you can also call <utility>the given
meaning of a template function: make_pair. make_pair requires two parameters, respectively, the first element and the last element of the element.
example:

pair <string,double> product3;
product3 = make_pair ("shoes",20.0);
cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";

The output:
of The Shoes IS. Price of $ 20.0

Note:
General make_pair parameters are used to make the required pair of position, you can call make_pair generate pair object directly.
Another aspect is the use of pair acceptable implicit type conversion, so that higher flexibility can be obtained. But such a problem arises:
for example, the following two definitions:

   std::pair<int, float>(1, 1.1);
        std::make_pair(1, 1.1);

Wherein a first of the second variable is a float type, sec make_pair function will add a link description ond variables are converted into double.
This problem is programming that require attention.

STL set

Quote from c ++ set Detailed usage

(1) set of definitions:

Headers<set>
on set, it must be said set associative containers. is set as a container for storing the same data type data type, and retrieves data from a data set, the value of each element are unique, but the system can be automatically sorted according to the value of the element in the set. It should be noted that the value of the number of elements in the set can not be changed directly. Standard C ++ STL associated with the container set, multiset, map, multimap inside a very efficient use is balanced binary tree retrieval: red-black tree, the tree has become RB (Red-Black Tree). RB trees statistical performance is better than that generally balanced binary tree, it was selected as the internal structure of the STL associated container.
Define a set objects:

set<int> s;
set<double> ss;

(2) set of basic operations:

s.begin()       // 返回指向第一个元素的迭代器
s.clear()       // 清除所有元素
s.count()       // 返回某个值元素的个数
s.empty()       // 如果集合为空,返回true(真)
s.end()         // 返回指向最后一个元素之后的迭代器,不是最后一个元素
s.equal_range()  // 返回集合中与给定值相等的上下限的两个迭代器
s.erase()       // 删除集合中的元素
s.find()        // 返回一个指向被查找到元素的迭代器
s.get_allocator() // 返回集合的分配器
s.insert()       // 在集合中插入元素
s.lower_bound()  // 返回指向大于(或等于)某值的第一个元素的迭代器
s.key_comp()    // 返回一个用于元素间值比较的函数
s.max_size()    // 返回集合能容纳的元素的最大限值
s.rbegin()       // 返回指向集合中最后一个元素的反向迭代器
s.rend()         // 返回指向集合中第一个元素的反向迭代器
s.size()        // 集合中元素的数目
s.swap()         // 交换两个集合变量
s.upper_bound()      // 返回大于某个值元素的迭代器
s.value_comp()  // 返回一个用于比较元素间的值的函数

Example:

#include <iostream>
#include <set>
 
using namespace std;
 set<int>s;
    s.insert(1);
    s.insert(2);
    s.insert(4);
    s.insert(0);
    cout<<"set 的 size 值为 :"<<s.size()<<endl;
    cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;
    cout<<"set 中的第一个元素是 :"<<*s.begin()<<endl;
     cout<<"set 中的最后一个元素是:"<<*s.end()<<endl;
     if(s.empty())
     {
         cout<<"set 为空 !!!"<<endl;
     }
     else cout<<"set 的 size 值为 :"<<s.size()<<endl;
     s.clear();
     if(s.empty())
     {
         cout<<"set 为空 !!!"<<endl;
     }
     else cout<<"set 的 size 值为 :"<<s.size()<<endl;
     cout<<"set 的 size 值为 :"<<s.size()<<endl;
     cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;
     return 0;
}

Operating results
set of size values:. 4
MAXSIZE set of values: 214748364
first elements in this set are: 0
last element in the set is:. 4
set of size values:. 4
set is empty! ! !
The size is set: 0
MAXSIZE set of values: 214748364

rbegin () and rend ()

Iterator
reverse iterator

Reverse iterator is an iterative traversal inverting the container. That is, from the last element to the first element to traverse the container. Reverse iterator will increment (and decrement) the meaning of the turn: For the reverse iterator ++ operator access to the previous element, and - calculating the next element is accessed.

.begin () returns an iterator that points to the first element of the container c
.end () returns an iterator, which points to the next position of the last element of the container c
.rbegin () Returns a reverse iterator pointing to the last element of the container c
foregoing .rend () returns a reverse iterator that points to the first element of the container c position

Iterator for indicating reverse range, and the range indicated is asymmetric, this fact can be derived an important conclusion: when == using reverse common iterator iterator to initialize or assign, the resulting iteration It is not the point to elements of the original iterator points to. ==

set traversal

#include<cstdio>  
#include<set>  
using namespace std;  
int main()  
{  
    set<int>s;  
    s.insert(3);   
    s.insert(1);  
    s.insert(2);  
    s.insert(1);  
    set<int>::iterator it;              
    for(it=s.begin();it!=s.end();it++)  //使用迭代器进行遍历   
    {  
        printf("%d\n",*it);  
    }  
    return 0;  
}  
//输出结果 : 1 2 3     一共插入了4个数,但是集合中只有3个数并且是有序的,可见之前说过的set集合的两个特点,有序和不重复。

Summary: Also note begin () and end () function does not check whether the set is empty, it is best to use before using empty () check to see if set is empty.

### count()

Used to look up a number in a set of keys appear. This function is not very practical in the set, as a key value may appear only in set 0 or 1, so that it becomes a judgment whether there is a key value in the set before.
example:

#include <iostream>
#include <set>
 
using namespace std;
 
int main(){
     set<int> s;
     s.insert(1);
     s.insert(2);
     s.insert(3);
     s.insert(1);
     cout<<"set 中 1 出现的次数是 :"<<s.count(1)<<endl;
     cout<<"set 中 4 出现的次数是 :"<<s.count(4)<<endl;
     return 0;
}

Results
number 1 appears in the set are: 1
times in the set is four occurring: 0

equal_range()

Returns a pair of locators, represent the first element is greater than or equal to the given key value and the first element greater than a given critical value, the return value is a pair type, if the return of the locator which fails , will be equal to the end () value.
example:

#include <iostream>
#include <set>
using namespace std;

int main()
{
    set<int>s;
    set<int>::iterator ter;
    for(int i=1;i<5;i++)
        s.insert(i);
     pair<set<int>::const_iterator,set<int>::const_iterator> pr;
     pr = s.equal_range(3);
     cout<<"第一个大于等于 3 的数是 :"<<*pr.first<<endl;
     cout<<"第一个大于 3的数是 : "<<*pr.second<<endl;
    return 0;
}

The results
of a number greater than or equal to 3 are: 3
the first number is greater than 3: 4

erase()

ERASE (iterator) , remove the locator point iterator value
ERASE (first, SECOND) , delete the value between the first retainer and SECOND
ERASE (key_value) , delete the value of the key key_value
Example:

#include <iostream>
#include <set>

using namespace std;

int main(){
     set<int> s;
     set<int>::const_iterator iter;
     set<int>::iterator first;
     set<int>::iterator second;
     for(int i = 1 ; i <= 10 ; ++i)
     {
         s.insert(i);
     }
     for(iter = s.begin() ; iter != s.end() ; ++iter)
     {
         cout<<*iter<<" ";
     }
     cout<<endl;
     //第一种删除
     s.erase(s.begin());
     //第二种删除
     first=s.begin();
     second=s.begin();
     second++;
     second++;
     s.erase(first,second);
     //第三种删除
     s.erase(8);
    cout<<"删除后 set 中元素是 :"<<endl;
     for(iter = s.begin() ; iter != s.end() ; ++iter)
     {
         cout<<*iter<<" ";
     }
     cout<<endl;
    return 0;
}

Results:
12345678910
after deleting elements are set:
4567910

Summary: delete operation is not set in any of the error checking, such as the legality of the positioners, etc., so time must pay attention to their own use.

insert()

INSERT (key_value)
the key_value inserted into the set, the return value is a pair <set :: iterator, bool>, bool marks the insert is successful, and iterator represents the insertion position, if key_value has been set, then the iterator key_value represented in the set position of.
the inset from (first, second)
the positioner to the first element is inserted into between the second set, the return value is void.
Example:

#include <iostream>
#include <set>

using namespace std;

int main()
{
     int a[] = {1,2,3};
     int t;
     set<int> s;
     set<int>::iterator iter;
     s.insert(a,a+3);
     for(iter = s.begin() ; iter != s.end() ; ++iter)
     {
         cout<<*iter<<" ";
     }
     cout<<endl;
     pair<set<int>::iterator,bool> pr;
     cin>>t;
     pr = s.insert(t);
     if(!pr.second)
     {
         cout<<"error"<<endl;
     }
     for(iter = s.begin() ; iter != s.end() ; ++iter)
     {
         cout<<*iter<<" ";
     }
     cout<<endl;
     return 0;
}

lower_bound&& upper_bound

lower_bound (key_value) , greater than or equal key_value returns the first locator
upper_bound, (key_value) , returns the last locator is greater than equal key_value
Example:


#include <iostream>
#include <set>
 
using namespace std;
 
int main()
{
     set<int> s;
     s.insert(1);
     s.insert(3);
     s.insert(4);
     cout<<*s.lower_bound(2)<<endl;
     cout<<*s.lower_bound(3)<<endl;
     cout<<*s.upper_bound(3)<<endl;
     return 0;
}

Results:
3
3
4

.find()

Find (Key) function is returned to the position of the key elements of the Key, the return value is an iterator type
Example

#include <iostream>
#include <set>
using namespace std;

int main()
{
    set<int>s;
    for(int i=0;i<10;i++)
        s.insert(i);
    set<int>::iterator it1=s.find(4);
    set<int>::iterator it2=s.find(11);
    if(it1!=s.end())
        cout<<*(it1)<<endl;
    else cout<<"error"<<endl;
    if(it2!=s.end())
        cout<<*(it2)<<endl;
    else cout<<"error"<<endl;
    return 0;
}

Result
4
error

.swap()

Two sets of exchange
Example

#include <iostream>
#include <set>
using namespace std;

int main()
{
    set<int>s1;
    set<int>s2;
    for(int i=0;i<10;i++)
        s1.insert(i);
    for(int i=10;i<15;i++)
        s2.insert(i);
    cout<<"s1:";
    for(set<int>::iterator it =s1.begin();it!=s1.end();it++)
        cout<<*(it)<<" ";
    cout<<endl;
    cout<<"s2:";
    for(set<int>::iterator it =s2.begin();it!=s2.end();it++)
        cout<<*(it)<<" ";
    cout<<endl;
    s1.swap(s2);//进行交换
    cout<<"s1:";
    for(set<int>::iterator it =s1.begin();it!=s1.end();it++)
        cout<<*(it)<<" ";
    cout<<endl;
    cout<<"s2:";
    for(set<int>::iterator it =s2.begin();it!=s2.end();it++)
        cout<<*(it)<<" ";
    cout<<endl;
    return 0;
}

Results
S1: 2. 3. 1 0. 4. 5. 6. 7. 8. 9
S2: 12 is 13 is 14 10. 11
S1: 12 is 13 is 14 10. 11
S2: 0. 5. 4. 3. 1 2. 6. 7. 8. 9

key_comp().value_comp()

Two types of functions in the set use the same
, but different types of return
key_comp () is a type key_compare
value_comp () is a type value_compare
Example

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
    set<double>s;
    for(int i=0;i<10;i++)
        s.insert(i);
    set<double>::key_compare kc1=s.key_comp();
    cout<<"s1:"<<endl;
    for(set<double>::iterator it=s.begin();it!=s.end();it++)
      {
          cout<<*(it)<<" ";
          if(kc1(7,*(it))==true) break;
      }
    cout<<endl;
    return 0;
}

Results
S1:
0. 5. 4. 3. 1 2. 8. 6. 7

Custom comparison function

(1) element is not the structure:

Example
// custom comparison function myComp, Overload "()" operator

struct myComp  
{  
    bool operator()(const your_type &a,const your_type &b)  
    {  
        return a.data-b.data>0;  
    }  
}  
set<int,myComp>s;  
......  
set<int,myComp>::iterator it;  
(2) if the element is the structure, the comparison function can be written directly in the structure.

Case

struct Info  
{  
    string name;  
    float score;  
    //重载“<”操作符,自定义排序规则  
    bool operator < (const Info &a) const  
    {  
        //按score从大到小排列  
        return a.score<score;  
    }  
}  
set<Info> s;  
......  
set<Info>::iterator it;  

Case

#include<stdio.h>  
#include<set>  
#include<string>  
using namespace std;  
struct People  
{  
    string name;  
    int age;  
    bool operator <(const People p) const  //运算符重载   
    {  
        return age<p.age;       //按照年龄由小到大进行排序   
    }  
};   
int main()  
{     
    set<People>s;  
    s.insert((People){"张三",14});  
    s.insert((People){"李四",16});  
    s.insert((People){"王二麻子",10});  
    set<People>::iterator it;              
    for(it=s.begin();it!=s.end();it++)  //使用迭代器进行遍历   
    {  
        printf("姓名:%s 年龄:%d\n",(*it).name.c_str(),(*it).age);  
    }  
    return 0;  
}  

The results
Name: Wang Asako Age: 10
Name: Joe Smith Age: 14
Name: John Doe Age: 16

multiset is another type of container with the keyword data file is the same value, and set different, it may contain duplicate elements, set and its usage is similar.

About map

In the header file in STL <map>defined template class map and multimap, with ordered binary tree table storing type
pair <const Key, T> sequence elements. Sequence const Key elements are identified as part of, map all of the elements in the Key
value must be unique, multimap Key duplicate values are allowed.
The map can be viewed as a collection of elements Key elements of identity, such containers are also known as "associative containers" can quickly determine the value of an element by a Key, so it is suitable for the need to find a container element in accordance with the Key value.
map template class template requires four parameters, the first one is the key type, the second element type, the third is the comparison operator, a fourth type dispenser. Which key type and element type is necessary.

Definition of map objects:

Example:

map<string, int> m;

The basic operation of the map:

/* 向map中插入元素 */
m[key] = value; // [key]操作是map很有特色的操作,如果在map中存在键值为
key的元素对, 则返回该元素对的值域部分,否则将会创建一个键值为key的元素对,值域为默认值。
所以可以用该操作向map中插入元素对或修改已经存在的元素对的值域部分。
m.insert(make_pair(key, value)); // 也可以直接调用insert方法插入元素对,insert操作会返回一个pair,当map中没有与key相匹配的键值时,其first是指向插入元素对的迭代器,其second为true;若map中已经存在与key相等的键值时,其first是指向该元素对的迭代器,second为false。
/* 查找元素 */
int i = m[key]; // 要注意的是,当与该键值相匹配的元素对不存在时,会创建键值为key(当另一个元素是整形时,m[key]=0)的元素对。
map<string, int>::iterator it = m.find(key); // 如果map中存在与key相匹配的键值时,find操作将返
回指向该元素对的迭代器,否则,返回的迭代器等于map的end()。
/* 删除元素 */
m.erase(key); // 删除与指定key键值相匹配的元素对,并返回被删除的元素的个数。
m.erase(it); // 删除由迭代器it所指定的元素对,并返回指向下一个元素对的迭代器。
/* 其他操作 */
m.size(); // 返回元素个数
m.empty(); // 判断是否为空
m.clear(); // 清空所有元素

Example:

#include<iostream>
#include<cstdio>
#include<map>
#include<utility>
using namespace std;
typedef pair<int,int>mypair;
int main()
{
    map<int,int>m;
    if(m.empty()) cout<<"empty"<<endl;
    else cout<<"m.size:"<<m.size()<<endl;
    m[1]=2;
    cout<<"m1:"<<m[1]<<endl;
    cout<<"m.size:"<<m.size()<<endl;
    /*
    cout<<m[3]<<endl;
    m.insert(mypair(3,6));
    cout<<m[3]<<endl;
    */  //插入失败
    m.insert(mypair(3,6));
    cout<<"m3:"<<m[3]<<endl;
    map<int,int>::iterator it1;
    pair<int,int>temp;
    it1=m.find(3);
    temp=*(it1);
    cout<<"m3.key:"<< temp.first <<" m3.value:"<<temp.second<<endl;
    m.erase(3);
    cout<<"m3:"<<m[3]<<endl;
    it1=m.find(1);
    m.erase(it1);
    cout<<"m1:"<<m[1]<<endl;
    cout<<"m.size:"<<m.size()<<endl;
    if(m.empty()) cout<<"empty"<<endl;
    else cout<<"m.size:"<<m.size()<<endl;
    m.clear();
    if(m.empty()) cout<<"empty"<<endl;
    else cout<<"m.size:"<<m.size()<<endl;
    return 0;
}

Other operations map of

(1)
Constructor Remark
map c/multimap c Generates an empty map or multimap, does not contain any factor
folder c (at) / Multimap c (at) Op is to sort criteria, generates an empty map / multimap
map c1(c2)/multimap c1(c2) Produce a copy of a map / multimap object, all the elements are copied
map c(beg,end)/multimap c(beg,end) In the element in the section (beg, end) to generate a new map / multimap
map c(beg,end,op)/multimap c(beg,end,op) In the element in the section (beg, end) to generate a new map / multimap, ranking criteria for the op
map effect
map<key,Elem> In less <> for the ordering criterion
map<key,Elem,op> Op is to sort criterion
Similarly multimap

Case

#include <iostream>
#include<map>
using namespace std;
typedef pair<int,double> CustomPair;
int main()
{
    map<int,double> m1;
    map<int,double,greater<int> >m2;
    map<int,double>::iterator it1;
    map<int,double,greater<int> >::iterator it2;
    m1.insert(CustomPair(1,2.0));
    m1.insert(CustomPair(2,3.0));
    m1.insert(CustomPair(3,4.0));
    cout<<"m1:"<<endl;
    for(it1=m1.begin();it1!=m1.end();it1++)
    {
        CustomPair p1=(pair<int,double>)(*it1);
        cout<<p1.first<<", ";
        cout<<std::fixed<<cout.precision(2)<<p1.second<<"; "<<endl;
    }
    m2.insert(CustomPair(1,2.0));
    m2.insert(CustomPair(2,3.0));
    m2.insert(CustomPair(3,4.0));
    cout<<"m2:"<<endl;
    for(it2=m2.begin();it2!=m2.end();it2++)
    {
        CustomPair p2=(pair<int,double>)(*it2);
        cout<<p2.first<<", ";
        cout<<std::fixed<<cout.precision(2)<<p2.second<<"; "<<endl;
    }
    return 0;
}

Results:
M1:
. 1, 62.00;
2, 23.00;
. 3, 24.00;
M2:
. 3, 24.00;
2, 23.00;
. 1, 22.00;

(2)

MAX_SIZE (); Maximum Capacity Output
Example:


int main()
{
    map<int,int>m;
    cout<<"max_size="<<m.max_size()<<endl;
    return 0;
}

The results:
MAX_SIZE = 178.95697 million

(3) count the number of random access

count ();
Function: Returns the number of elements appear in the map.

upper_bound (), lower_bound ();
Function:
upper_bound, (key) of the return value is greater than an iterator directed key element; lower_bound () return a pointer to the return value is an iterator front key elements.
example:

#include <iostream>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<int,double> CustomPair;
int main()
{
    map<int,double> m1;
    map<int,double,greater<int> >m2;
    map<int,double>::iterator it1;
    map<int,double,greater<int> >::iterator it2;
    CustomPair temp;
    m1.insert(CustomPair(1,2.0));
    m1.insert(CustomPair(2,3.0));
    m1.insert(CustomPair(3,4.0));
    cout<<"m1:"<<endl;
    for(it1=m1.begin();it1!=m1.end();it1++)
    {
        CustomPair p1=(pair<int,double>)(*it1);
        cout<<p1.first<<", ";
        cout<<std::fixed<<cout.precision(2)<<p1.second<<"; "<<endl;
    }
    m2.insert(CustomPair(1,2.0));
    m2.insert(CustomPair(2,3.0));
    m2.insert(CustomPair(3,4.0));
    cout<<"m2:"<<endl;
    for(it2=m2.begin();it2!=m2.end();it2++)
    {
        CustomPair p2=(pair<int,double>)(*it2);
        cout<<p2.first<<", ";
        cout<<std::fixed<<cout.precision(2)<<p2.second<<"; "<<endl;
    }
    cout<<"1 in m1="<<m1.count(1)<<endl;
    it1=m1.upper_bound(2);
    temp=*it1;
    cout<<"upper_bound(2)--->"<<temp.first<<","<<temp.second<<endl;
    it1=m1.lower_bound(2);
    temp=*it1;
    cout<<"lower_bound(2)--->"<<temp.first<<","<<temp.second<<endl;
    return 0;
}

结果:
m1:
1, 62.00
2, 23.00
3, 24.00
m2:
3, 24.00
2, 23.00
1, 22.00
1 in m1 =1
upper_bound(2)--->3,4.00
lower_bound(2)--->2,3.00

Guess you like

Origin www.cnblogs.com/springfield-psk/p/12080965.html