交换功能。 ?! [英] Swapping Function. ?!
本文介绍了交换功能。 ?!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以向我解释,或者甚至告诉我如何编写一个交换两个指定数组元素值的完整函数。
例如,
Can someone explain to me, or even show me how to write a complete function that swaps the values of "two specified array elements."
For instance,,
// Selection_Sort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void fill(int a[], int length)
{
for (int i = 0; i < length; i++)
{
cout << "Element #" << i+1 << endl;
cin >> a[i];
}
cout << '\n' << endl;
}
void print(int a[], int length)
{
cout << "A R R A Y Of 10 Elements Are As." << endl;
for (int j = 0; j < length; j++)
{
cout << a[j] << " | ";
}
cout << '\n' << endl;
}
void swap(int &x, int &y)
{
int temp;
temp = a[x];
a[x] = a[y];
a[y] = temp;
}
void selectionSort(int a[], int length)
{
int i, j;
int min, temp;
for (i = 0; i < length-1; i++)
{
min = i;
for (j = i+1; j < length; j++)
{
if (a[j] < a[min])
min = j;
}
/*temp = a[i];
a[i] = a[min];
a[min] = temp;*/
swap(a[i], a[min];
}
}
int main()
{
const int length = 10;
int label[length];
fill(label, length);
print(label, length);
selectionSort(label, length);
print(label, length);
system("pause");
return 0;
}
特别要求尊敬的OriginalGriff,请详细说明。!!
任何建议都会受到赞赏。!!
Especially it is requested to respected OriginalGriff, Please eloborate. !!
Any Suggestions Will Be Appreciated . !!
推荐答案
一般来说你在找东西喜欢(C ++ 11):
In general you''re looking for something like (C++11):
template <class T> void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
template <class T, size_t N> void swap (T &a[N], T &b[N])
{
for (size_t i = 0; i<N; ++i) swap (a[i],b[i]);
}
其中T必须是可复制构造且可分配的。
这也是什么std :: swap适合你。
最好的问候
Espen Harlinn
where T must be copy-constructible and assignable.
This is also what std::swap does for you.
Best regards
Espen Harlinn
这篇关于交换功能。 ?!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文