How to use the pair of C + + learning _c language

Source: Internet
Author: User

Overview of pair types

Pair is a template type that contains two data values, and two types of data can be different, basically defined as follows:

Pair<int, string> A;

Indicates that there are two types in a, the first element is type int, the second element is string, and if it is not initialized when pair is created, the default constructor is invoked to initialize it.

Pair<string, string> A ("James", "Joy");

It can also be initialized directly to the definition as above.

Because the use of pair types is cumbersome, because if you want to define multiple pair types, the typedef can simplify the declaration:

typedef pair<string, string> author;
Author Pro ("May", "Lily");
Author Joye ("James", "Joyce");

two ,the pair object operation

1, for the pair class, because it has only two elements, named First and second respectively, so directly using the ordinary point operator to access its members

Pair<string, string> A ("Lily", "Poly"); 
string name;
name = Pair.second;

2, the generation of new pair objects

You can use Make_pair to construct a new pair type for existing two data:

int a = 8;
string m = "James";
Pair<int, string> Newone;
Newone = Make_pair (A, m);

Third, the programming practice

Practice: Write a program that reads a series of string and int data, stores each group in a pair object, and then stores the pair objects in a vector container

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

int main ()
{
  pair<string, int>p;
  typedef vector< pair<string, int> > VP;
  VP VP;
  while (Cin>>p.first>>p.second)
  {
    vp.push_back (Make_pair (P.first,p.second));
    
  }
  Vp::iterator it;
  For (It=vp.begin (); It!=vp.end (); it++)
    cout<<it->first<< "," <<it->second<<endl ;

  return 0;
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.