task3_1.cpp
#include <iostream> #include <fstream> #include <array> #define N 5 int main() { using namespace std; array<int, N> x {97, 98, 99, 100, 101}; ofstream out; out.open("data1.dat", ios::binary); if(!out.is_open()) { cout << "fail to open data1.dat\n"; return 1; } out.write(reinterpret_cast<char *>(&x), sizeof(x)); out.close(); }
task3_2.cpp
#include <iostream> #include <fstream> #include <array> #define N 5 int main() { using namespace std; array<char, N> x; ifstream in; in.open("data1.dat", ios::binary); if(!in.is_open()) { cout << "fail to open data1.dat\n"; return 1; } in.read(reinterpret_cast<char *>(&x), sizeof(x)); in.close(); for(auto i = 0; i < N; ++i) cout << x[i] << ", "; cout << "\b\b \n"; }
char型占用1字节,int型占用4个字节。转换成char字符时,a只占1个字符,所以产生空格。
Vector.hpp
#include<iostream> using namespace std; template<typename T> class Vector{ public: Vector(int n); Vector(int n,T value); Vector(const Vector<T>& v); T get_size(); T& at(int index); T& operator[](int i); template<typename A> friend void output(const Vector<A>& v); private: int size; T *p; }; template<typename T> Vector<T>::Vector(int n):size{n} { p=new T[n]; } template<typename T> Vector<T>::Vector(int n,T value):size{n} { p=new T[n]; for(auto i=0;i<size;i++) p[i]=value; } template<typename T> Vector<T>::Vector(const Vector<T>& v):size{v.size} { p=new T[size]; for(auto i=0;i<size;i++) p[i]=v.p[i]; } template<typename T> T Vector<T>::get_size() { return size; } template<typename T> T& Vector<T>::at(int index) { return p[index]; } template<typename T> T& Vector<T>::operator[](int i) { return p[i]; } template<typename A> void output(const Vector<A>& v) { for(auto i=0;i<v.size;i++) cout<<v.p[i]<<", "; cout<<"\b\b \n"; }
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(); }
task5.cpp
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
void output(std::ostream& output)
{
output << " ";
for (int i = 97; i < 123; i++)
{
output << setw(2) << char(i);
}
output << endl;
for (int i = 1; i <= 26; i++)
{
output << setw(2) << i;
int j;
for (j=i;j<i+26;j++)
{
output<<setw(2)<<char(65+j%26);
}
output << endl;
}
}
int main()
{
ofstream out;
output(cout);
out.open("cipher_key.txt");
output(out);
return 0;
}
标签:int,Vector,实验,output,include,out,size From: https://www.cnblogs.com/mzxfcyt/p/16948159.html