task3_1
#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
#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"; }
运行截图
int类型占四个字节,但97等只保存在一个地址空间里,其余三个字节保存0,char类型占一个字节,读入char类型数组时,第一次读到97,转化为a,接下来读到数据为空,直到第五个读到98,变为b,结束
vector.hpp
#pragma once #include<iostream> using namespace std; template<class T> class Vector { public: Vector() { } Vector(int n) { p = new T[n]; size = n; } Vector(int n,T value) { p = new T[n]; for (int i = 0; i < n; i++) { p[i] = value; } size = n; } Vector(const Vector<T> &vec) { p = new T[vec.get_size()]; for (int i = 0; i < vec.get_size(); i++) { p[i] = vec.p[i]; } size = vec.size; } ~Vector(){ delete p; } int get_size() const; T& at(int index); T& operator[](int index); template<typename T> friend void output(Vector<T> vec); private: T* p; int size; }; template<class T> int Vector<T>::get_size() const{ return size; } template<class T> T& Vector<T>::at(int index) { return p[index]; } template<class T> T& Vector<T>::operator[](int index) { return p[index]; } template<class T> void output(Vector<T> vec) { for (int i = 0; i < vec.get_size(); i++) { cout << vec.p[i] << " "; } cout << endl; }
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
#include<iostream> using namespace std; #include<fstream> void output(ofstream& out); int main() { ofstream out; out.open("cipher_key.txt", ios::out); output(out); } void output(ofstream& out) { cout << " "; out << " "; for (int i = 0; i < 26; i++) { char c = i + 'a'; cout <<" " << c; out <<" "<< c; } cout << endl; out << endl; for (int i = 1; i<=26; i++) { cout << i; out << i; for (int j = i; j < i+26; j++) { char c = 'A' + j%26; cout << " " << c; out << " " << c; } cout << endl; out << endl; } }
标签:int,Vector,实验,output,include,out,size From: https://www.cnblogs.com/Zhouzhou-/p/16948925.html