Algorithms notes - Standard Template Library STL - pair

A common use of pair

It is a very useful pair of "gadgets", when it is desired to tie together two elements as a composite element, and therefore do not want the definition of the structure, can easily use the pair as a substitute. That is, a pair can be considered as two elements of internal structure, and these two types of elements can be specified as the following short code:

struct pair{
    typeName1 first;
    typeName2 second;
}

Defined pair of

head File

#include<utility>	 
using namespace std;

Since when have used the map to realize pair, so remember utility, you can use the map header files

definition

pair<typeName1, typeName2> name;

pair<string, int> p;

If you want to initialize when defining pair, just to keep up with a small parenthesis

pair<string, int> p("gqq", 5);

If you want to build in the code 临时的pair , there are two ways:

  1. The embodiment of the two element type definition EDITORIAL parentheses, followed by
pair<string, int>("gqq", 5);
  1. Use its ownmake_pair函数
make_pair("gqq", 5);

Access pair of elements

Only two elements in pair, respectively, first and second, only need a normal installation structure to access

#include<iostream>
#include<utility>
#include<string>
using namespace std;

int main(){
    pair<string, int> p;
    p.first = "zgq";
    p.second = 5;
    cout << p.first << " " << p.second << endl;
    p = make_pair("yzy", 55);
    cout << p.first << " " << p.second << endl;
    p = pair<string, int>("wjy", 555);
    cout << p.first << " " << p.second << endl;
    return 0;
}
zgq 5
yzy 55
wjy 555

pair commonly used functions

Comparison of operands

Two types of data pair can directly ==、!=、<、<=、>、>=compare the size comparison rule is first in first size as a standard, only when the first size is equal to judge if the second

#include<iostream>
#include<utility>
#include<string>
using namespace std;

int main(){
    pair<int, int> p1(5, 10);
    pair<int, int> p2(5, 15);
    pair<int, int> p3(10, 5);
    if(p1 < p3) printf("p1 < p3\n");
    if(p1 <= p3) printf("p1 <= p3\n");
    if(p1 < p2) printf("p1 < p2\n");
    return 0;
}
p1 < p3
p1 <= p3
p1 < p2

Common uses pair of

  1. Used in place of the dual structure member and constructors, it can save time coding
  2. As for the keys of the map to be inserted
#include<iostream>
#include<map>
#include<string>
using namespace std;

int main(){
    map<string, int> mp;
    mp.insert(make_pair("gqq", 5));
    mp.insert(pair<string, int>("yzy", 10));
    for(map<string, int>::iterator it = mp.begin(); it != mp.end(); it++){
        cout << it -> first << " " << it -> second << endl;

    }
    return 0;
}
gqq 5
yzy 10

Write by Gqq

Guess you like

Origin www.cnblogs.com/zgqcn/p/12590908.html