• 主页
taozhangzhi9 2003年06月27日
##### Tuples (这是本人翻译的第一篇文章，希望大家批评指导，陶章志)
Tuples
Herb Sutter

1 是Doug Gregor’s提出的多态函数的object wrappers。
2 Jaakko Järvi's提出的tuple类型。

Tuple Types：一个简单Motivating例子

// yields a quotient only
//
int IntegerDivide( int n, int d ) {
return n / d;
}

// Sample use:
cout << "quotient = " << IntegerDivide( 5, 4 );

// Example 1(b): Integer division,
// yielding a quotient and remainder,
// one as the return value and one via
// an output parameter
//
int IntegerDivide( int n, int d, int& r ) {
r = n % d;
return n / d;
}
// Sample use:
int remainder;
int quotient = IntegerDivide( 5, 4, remainder );
cout << "quotient = " << quotient
<< "remainder = " << remainder;

// Example 1(c): Integer division,
// yielding a quotient and remainder,
// this time via two output parameters
//
void IntegerDivide( int n, int d, int& q, int& r ) {
r = n % d;
q = n / d;
}

// Sample use:
int quotient, remainder;
IntegerDivide( 5, 4, quotient, remainder );
cout << "quotient = " << quotient
<< "remainder = " << remainder;

// Example 1(d): Integer division,
// yielding a quotient and remainder,
// this time both in the return value
//
std::pair<int,int> IntegerDivide( int n, int d ) {
return pair<int,int>( n/d, n%d );
}

// Sample use:
pair<int, int> quot_rem = IntegerDivide( 5, 4 );
cout << "quotient = " << quot_rem.first
<< "remainder = " << quot_rem.second;

Tuples in Action

type和“bundle-o-values”很相像。

// Example 2(a): Integer division,
// yielding a quotient and remainder,
// 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>();

// 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 ) {
// —
}

// 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;

// Example 4(a): Streaming tuples
//
tuple<int, int> quot_rem = IntegerDivide( 5, 4 );
cout << quot_rem; // "(1 1)"

// Example 4(b): Customizing streamed tuples
//
tuple<int, int> quot_rem = IntegerDivide( 5, 4 );
cout << tuples::set_open('['] << tuples::set_close(')')

<< tuples::set_delimiter(',')
<< quot_rem; // "[1,1]"

...全文
3 点赞 收藏 5

5 条回复

C语言

3.2w+

24.0w+

C语言相关问题讨论