"margin: 0cm 36pt 0pt">// via a type return type
//tuple<int,int> integerdivide( int n, int d ) {
return tuple<int,int>( n/d, n%d );} // sample use:tuple<int, int> quot_rem = integerdivide( 5, 4 );cout << "quotient = " << quot_rem.get<0>() << "remainder = " << quot_rem.get<1>();这个例子的语法没有pair那么优雅,但是,它却是和pairs一样的简单好用。另一方面,typle 不局限于只有两个成员,它可以有任意多的成员,因此,它可以捆绑任何多个数值,我们来看下面的例子:// example 2(b): floating-point division,// yielding a quotient and remainder,// but also an underflow//tuple<float, float, bool> // quotient, remainder, underflow
floatdivide( float n, float d ) {// —
}如果,我们使用std::pair来实现的话,那么将会是这样,std::pair<float, std::pair<float, bool> >, (译注:这样大家也许能够看出tuple的优势了把)但是,我们不能老是把tuple作为bundle-o-values来使用。这里有一些方法把来说怎样把一些独立的变量捆绑成tuple 。这是对于捆绑数值和解绑数值都是有用。例如,我们回到第一个关于除法例子 。
// example 3: bundling and unbundling// using "tie"//tuple<int,int> integerdivide( int n, int d ) { return tuple<int,int>( n/d, n%d );} // sample use:int quotient, remainder;tie( quotient, remainder ) = integerdivide( 5, 4 );
cout << "quotient = " << quotient<< "remainder = " << remainder;通过这种方法,我们就不用写那些我们不喜欢写的输出变量了,tuples有自己的输入,输出符号,和解压操作符号。// example 4(a): streaming tuples//tuple<int, int> quot_rem = integerdivide( 5, 4 );cout << quot_rem; // "(1 1)"