交换实施:效率和适用范围?
swap implementations: efficiency & range of applicability?
我试图涵盖所有 swap
函数实现。
在swap
函数的以下实现中不需要临时变量来交换两个参数的值:
void swapNoTemp1(int &a, int &b){
a = a + b;
b = a - b;
a = a - b;
}
或
template <class T>
void swapNoTemp2(T& i, T& j){
i -= j;
j += i;
i = (j - i);
}
或
void swapNoTemp3(int &a, int &b){
a ^= b;
b ^= a;
a ^= b;
}
因此,就使用的内存而言,它比:
更有效
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
另一方面,swap
可以使用以下方式实现:
void swapPointers(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
我正在尝试比较所有现有的实现并了解它们的适用范围。
第一个函数的行为未定义。运算可能会导致溢出,在某些机器上,溢出会导致异常。
标准规定:
If during the evaluation of an expression, the result is not mathematically defined or not in the range of
representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++
ignore integer overflows. ... ]
尽管在实践中您很有可能会使用该功能,但最好避免使用它。
我试图涵盖所有 swap
函数实现。
在swap
函数的以下实现中不需要临时变量来交换两个参数的值:
void swapNoTemp1(int &a, int &b){
a = a + b;
b = a - b;
a = a - b;
}
或
template <class T>
void swapNoTemp2(T& i, T& j){
i -= j;
j += i;
i = (j - i);
}
或
void swapNoTemp3(int &a, int &b){
a ^= b;
b ^= a;
a ^= b;
}
因此,就使用的内存而言,它比:
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
另一方面,swap
可以使用以下方式实现:
void swapPointers(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
我正在尝试比较所有现有的实现并了解它们的适用范围。
第一个函数的行为未定义。运算可能会导致溢出,在某些机器上,溢出会导致异常。
标准规定:
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. ... ]
尽管在实践中您很有可能会使用该功能,但最好避免使用它。