作業題:



7. 填空(2分)簡單的swap 通過碼是 ( 請參考公告中的“關於編程作業的說明”完成編程作業(請注意,編程題都要求提交通過碼,在openjudge上提交了程序並且通過以后,就可以下載到通過碼。)
總時間限制: 1000ms 內存限制: 65536kB
描述 :填空,使得程序 輸出結果是:5,3
#include <iostream>
using namespace std;
class A
{
public:
int x;
int getX() { return x; }
};
void swap(
// 在此處補充你的代碼
)
{
int tmp = a.x;
a.x = b.x;
b.x = tmp;
}
int main()
{
A a,b;
a.x = 3;
b.x = 5;
swap(a,b);
cout << a.getX() << "," << b.getX();
return 0;
}
輸入無 輸出5,3
答案:
#include <iostream>
using namespace std;
class A
{
public:
int x;
int getX() { return x; }
};
void swap( A & a, A & b) //考察定義到類型的問題
{
int tmp = a.x;
a.x = b.x;
b.x = tmp;
}
int main()
{
A a,b;
a.x = 3;
b.x = 5;
swap(a,b);
cout << a.getX() << "," << b.getX();
return 0;
}
8 填空(2分) 難一點的swap
填空,使得程序輸出結果是:5,3
#include <iostream>
using namespace std;
void swap(
// 在此處補充你的代碼
)
{
int * tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 3,b = 5;
int * pa = & a;
int * pb = & b;
swap(pa,pb);
cout << *pa << "," << * pb;
return 0;
}
答案:
#include <iostream>
using namespace std;
void swap(int *& a,int *& b)
{
int * tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 3,b = 5;
int * pa = & a;
int * pb = & b;
swap(pa,pb);
cout << *pa << "," << * pb;
return 0;
}
9 填空(2分) 好怪異的返回值
填空,使得程序輸出指定結果
#include <iostream>
using namespace std;
// 在此處補充你的代碼
getElement(int * a, int i)
{
return a[i];
}
int main()
{
int a[] = {1,2,3};
getElement(a,1) = 10;
cout << a[1] ;
return 0;
}
輸入 無 輸出 10
答案:
#include <iostream>
using namespace std;
int & getElement(int * a, int i)
{
return a[i];
}
int main()
{
int a[] = {1,2,3};
getElement(a,1) = 10;
cout << a[1] ;
return 0;
}
10 填空(2分) 神秘的數組初始化
#include <iostream>
using namespace std;
int main()
{
int * a[] = {
// 在此處補充你的代碼
};
*a[2] = 123;
a[3][5] = 456;
if(! a[0] ) {
cout << * a[2] << "," << a[3][5];
}
return 0;
}
輸入 無 輸出 123,456
答案:
#include <iostream>
using namespace std;
int main()
{
int * a[] = {0,0,new int[1],new int[1]};
*a[2] = 123;
a[3][5] = 456;
if(! a[0] ) {
cout << * a[2] << "," << a[3][5];
}
return 0;
}
