task4.cpp:
点击查看代码
#include <iostream>
#include "vector.hpp"
void test()
{
using namespace std;
int n;
cin >> n;
Vector<double> x1(n);
for (auto i = 0; i < n; ++i)
x1.at(i) = i * 0.7;
output(x1);
Vector<int> x2(n, 42);
Vector<int> x3(x2);
output(x2);
output(x3);
x2.at(0) = 77;
output(x2);
x3[0] = 999;
output(x3);
}
int main()
{
test();
}
vector.hpp:
点击查看代码
#include<iostream>
#include<stdexcept>
#include <cassert>
using namespace std;
template<typename T>
class Vector
{
private:
int size;
T* ptr;
public:
Vector(int size)
{
if (size < 0)
throw std::length_error("vector constructor:negative size");
this->size = size;
ptr = new T[this->size];
}
Vector(int size, T value)
{
if (size < 0)
throw std::length_error("vector constructor:negative size");
this->size = size; ptr = new T[size];
for (auto i = 0; i < size; i++)
{
ptr[i] = value;
}
}
Vector(const Vector<T>& x)
{
size = x.size;
ptr = new T[size];
for (auto i = 0; i < size; i++)
{
ptr[i] = x.ptr[i];
}
}
~Vector()
{
delete[] ptr;
}
int get_size() { return size; }
T& at(int i)
{
assert(i >= 0 && i < size);
return(ptr[i]);
}
T& at(int i) const
{
assert(i >= 0 && i < size);
return(ptr[i]);
}
T& operator[](int i)
{
return ptr[i];
}
friend void output(Vector<T> x)
{
for (auto i = 0; i < x.get_size(); i++)
cout << x.at(i) << ",";
cout << "\b\b\n";
}
};
task5.cpp
点击查看代码
#include<fstream>
#include<iostream>
#include<stdexcept>
#include<string>
#include <iomanip>
using namespace std;
void output(ostream& out)
{
int i, j;
string a[27][27];
for (i = 0;i < 27;i++)
{
for (j = 0;j < 27;j++)
{
if (i == 0 && j == 0)
{
a[i][j] = ' ';
out << a[i][j];
}
else if (i == 0)
{
a[i][j] = 'a' + j - 1;
out << a[i][j];
}
else if (j == 0)
{
a[i][j] = '1' + i - 1;
out << i;
}
else
{
a[i][j] = 'A' + (i + j + 26) % 26;
out << a[i][j];
}
}
}
}
int main()
{
cout << setiosflags(ios::left);
int i, j;
string a[27][27];
for (i = 0;i < 27;i++)
{
for (j = 0;j < 27;j++)
{
if (i == 0 && j == 0)
{
a[i][j] = ' ';
cout << a[i][j] << " ";
}
else if (i == 0)
{
a[i][j] = 'a' + j - 1;
cout << a[i][j] << " ";
}
else if (j == 0)
{
a[i][j] = '1' + i - 1;
cout << i << "\t\b\b\b\b\b";
}
else
{
a[i][j] = 'A' + (i + j + 26) % 26;
cout << a[i][j] << " ";
}
}
cout << endl;
}
cout << endl;
ofstream out;
out.open("cipher_key.txt");
if (!out.is_open())
{
std::cout << "fail to open file " << std::endl;
return 0;
}
output(out);
out.close();
}