(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Sorting Rational Numbers (P.508)
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
class CRational
{
public:
int numerator; // 分子
int denominator; // 分母
void Print()
{
cout << numerator << '/' << denominator << endl;
}
CRational(int p = 0, int q = 1)
{
numerator = p; denominator = q;
}
CRational operator+(CRational b) const // const member function (P.307)
{
return CRational( numerator*b.denominator + denominator*b.numerator,
denominator * b.denominator );
}
CRational& operator-(CRational b) // Return a reference (P.341)
{
numerator = numerator*b.denominator - denominator*b.numerator;
denominator = denominator * b.denominator;
return *this;
}
};
bool Less(CRational a, CRational b)
{
return a.numerator*b.denominator < b.numerator*a.denominator;
}
int main()
{
int b[] = { 1, 3, 5, 7, 2, 4, 6 };
vector<CRational> a;
for (size_t i=0; i<(sizeof b / sizeof b[0]); i++)
a.push_back( CRational(1, b[i]) );
sort(a.begin(), a.end(), Less);
for (size_t i=0; i<a.size(); i++)
a.at(i).Print();
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// String Methods (P.405)
#include <iostream>
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::string;
using std::cout;
using std::endl;
class CDiagonal {
public:
int x1;
int y1;
int x2;
int y2;
CDiagonal(int a=0, int b=0, int c=0, int d=0):
x1(a), y1(b), x2(c), y2(d) {}
};
string getDiagonal(vector<string> tabula, CDiagonal pos)
{
string s = string(1, tabula[pos.x1][pos.y1]) +
string(1, tabula[pos.x2][pos.y2]);
return s;
}
CDiagonal findDiagonal(vector<string> tabula, string s)
{ // s is a 2-character string
char c1 = s[0];
char c2 = s[1];
int x1, y1, x2, y2;
for (x1=0; x1<5; x1++)
{
y1 = tabula[x1].find(c1);
if (y1 != string::npos) break;
}
for (x2=0; x2<5; x2++)
{
y2 = tabula[x2].find(c2);
if (y2 != string::npos) break;
}
return CDiagonal(x1, y1, x2, y2);
}
string enc(string s, vector<string> tabula)
{
string ciphertext, c3c4;
CDiagonal pos, pos2;
for (size_t i=0; i<s.length()-1; i+=2)
{
pos = findDiagonal(tabula, s.substr(i,2));
pos2.x1 = pos.x1;
pos2.y1 = pos.y2;
pos2.x2 = pos.x2;
pos2.y2 = pos.y1;
c3c4 = getDiagonal(tabula, pos2);
ciphertext += c3c4;
}
return ciphertext;
}
int main()
{
string plaintext = "PXMMCTUBACSJNO";
string ciphertext;
string s("ABCDEFGHIJKLMNOPQRSTUVWXY");
vector<string> t;
for (size_t i=0; i<5; i++)
t.push_back(s.substr(i*5, 5));
ciphertext = enc(plaintext, t);
cout << ciphertext << endl;
return 0;
}