加文

希望是美好的……
随笔 - 0, 文章 - 209, 评论 - 0, 引用 - 0
数据加载中……

pair Class


template<class Type1, class Type2>
   struct pair 
   {
   typedef Type1 first_type;
   typedef Type2 second_type
   Type1 first;
   Type2 second;
   pair( );
   pair(
      const Type1& __Val1, 
      const Type2& __Val2
   );
   template<class Other1, class Other2>
      pair(
         const pair<Other1, Other2>& _Right
            );
   };
测试代码如下:// utility_pair.cpp
// compile with: /EHsc
#include <utility>
#include <map>
#include <iomanip>
#include <iostream>

int main( )
{
   using namespace std;

   // Using the constructor to declare and initialize a pair
   pair <intdouble> p1 ( 10, 1.1e-2 );

   // Compare using the helper function to declare and initialize a pair
   pair <intdouble> p2;
   p2 = make_pair ( 10, 2.22e-1 );

   // Making a copy of a pair
   pair <intdouble> p3 ( p1 );

   cout.precision ( 3 );
   cout << "The pair p1 is: ( " << p1.first << ", " 
        << p1.second << " )." << endl;
   cout << "The pair p2 is: ( " << p2.first << ", " 
        << p2.second << " )." << endl;
   cout << "The pair p3 is: ( " << p3.first << ", " 
        << p3.second << " )." << endl;

   // Using a pair for a map element
   map <intint> m1;
   map <intint>::iterator m1_Iter;

   typedef pair <intint> Map_Int_Pair;

   m1.insert ( Map_Int_Pair ( 1, 10 ) );
   m1.insert ( Map_Int_Pair ( 2, 20 ) );
   m1.insert ( Map_Int_Pair ( 3, 30 ) );

   cout << "The element pairs of the map m1 are:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " ( " << m1_Iter -> first << ", "
           << m1_Iter -> second << " )";
   cout   << "." << endl;

   // Using pair as a return type for a function
   pair< map<int,int>::iterator, bool > pr1, pr2;
   pr1 = m1.insert ( Map_Int_Pair ( 4, 40 ) );
   pr2 = m1.insert ( Map_Int_Pair (1, 10 ) );

   if( pr1.second == true )
   {
      cout << "The element (4,40) was inserted successfully in m1."
           << endl;
   }
   else   
   {
      cout << "The element with a key value of\n"
           << " ( (pr1.first) -> first ) = " << ( pr1.first ) -> first 
           << " is already in m1,\n so the insertion failed." << endl;
   }

   if( pr2.second == true )
   {
      cout << "The element (1,10) was inserted successfully in m1."
           << endl;
   }
   else   
   {
      cout << "The element with a key value of\n"
           << " ( (pr2.first) -> first ) = " << ( pr2.first ) -> first 
           << " is already in m1,\n so the insertion failed." << endl;
   }
}

posted on 2012-04-08 22:29 加文 阅读(167) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理