cplusplus系列>utility>pair

http://www.cplusplus.com/reference/utility/pair/

用于存储一对异构对象

// Compile: g++ -std=c++11 pair.cpp

#include <utility>
#include <string>
#include <iostream>
#include <tuple>

int main () {
  std::pair <std::string, int> p1;                                // default constructor
  p1 = std::make_pair(std::string("alpha"), 1);                   // using make_pair (move)
  std::pair <std::string, int> p2 ("beta", 2.01);                 // value init
  std::pair <std::string, int> p3 (p2);                           // copy constructor
  std::pair <std::string, int> p4 = p2;                           // assignment operator
  std::pair <std::string, int> p5(std::piecewise_construct,
                                  std::forward_as_tuple("omega"),
                                  std::forward_as_tuple(0));      // c++11, piecewise constructor

  p2.first = "gamma";
  p2.second = 'c';

  p1.swap(p4);                // c++11
  std::swap(p2, p3);          // c++11
  std::get<0>(p1) = "delta";  // c++11, get<0> means first
  std::get<1>(p1) = 4L;       // c++11, get<1> means second

  std::cout << "p1: (" << p1.first << ", " << p1.second << ")\n";
  std::cout << "p2: (" << p2.first << ", " << p2.second << ")\n";
  std::cout << "p3: (" << p3.first << ", " << p3.second << ")\n";
  std::cout << "p4: (" << std::get<0>(p4) << ", " << std::get<1>(p4) << ")\n";
  std::cout << "p5: (" << std::get<0>(p5) << ", " << std::get<1>(p5) << ")\n";

  return 0;
}

 

posted on 2013-09-12 13:44  chenkkkabc  阅读(316)  评论(0编辑  收藏  举报