求助 vector内元素互换!
写一个名为swapFrontBack的函数,整数输入vector内。该函数将第一个和第最后一个函数交换。这个函数可以检查vector是否是空的以防错误。用不同的长度测试你的函数。template<typename T>
int Swap(T* one, T* another) {
if (one == nullptr || another == nullptr) {
return 0;
}
if (one == another || *one == *another) {
return 0;
}
T temp = *one;
*one = *another;
*another = temp;
return 1;
}
template<typename T>
int SwapFrontBack(std::vector<T> &v) {
return Swap(&*v.begin(), &*(v.end()-1) );
}
void PrintInts(std::vector<int> &v) {
for (auto it = v.begin(); it != v.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
int main() {
{
std::vector<int> v{1, 2, 3, 4, 5};
PrintInts(v);
SwapFrontBack(v);
PrintInts(v);
}
{
std::vector<int> v{};
PrintInts(v);
SwapFrontBack(v);
PrintInts(v);
}
{
std::vector<int> v{1};
PrintInts(v);
SwapFrontBack(v);
PrintInts(v);
}
return 0;
} 赚小钱 发表于 2020-7-25 14:12
太感谢了!!!
页:
[1]