6.3
#include <iostream> #include <fstream> #include <array> #define N 5 void test1(){ 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"; } // 把从地址&x开始连续sizeof(x)个字节的数据块以字节数据块方式写入文件data1.txt out.write(reinterpret_cast<char*>(&x), sizeof(x)); out.close(); } void test2() { using namespace std; array<int, N> x; ifstream in; in.open("data1.dat", ios::binary); if (!in.is_open()) { cout << "fail to open data1.dat\n"; } // 从文件流对象in关联的文件data1.dat中读取sizeof(x)字节数据写入&x开始的地址单元 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 main() { test1(); test2(); return 0; }
修改后结果如下:
char型占1个字节,而int型占4个字节。
6.4
#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(); } #pragma once #include<iostream> using namespace std; template<typename T> class vector{ template<typename T> friend void output(vector<T>& v); public: vector(int n); vector(int n, T value); vector(const vector<T>& v) ; ~vector()=default; T& at(int i) const{ return vec[i]; }; T& operator[](int i)const { return vec[i]; }; int get_size()const { return size; }; private: int size; T* vec; }; //构造函数接口 template<typename T> vector<T>::vector(int n) { size = n; cout << "constructor called \n"; vec = new T[size]; } //构造函数接口 template<typename T> vector<T>::vector(int n, T value) { cout << "constructor called" << endl; size = n; vec = new T[size]; for (int i = 0; i < size; i++) { vec[i] = value; } } //复制构造函数接口 template<typename T> vector<T>::vector(const vector<T>& v) { cout << "copyconstructor called \n"; size = v.size; vec = new T[size]; for (int i = 0; i < size; i++) vec[i] = v.vec[i]; } //输出数组元素函数接口 template<typename T> void output(vector<T>& v) { for (int i = 0; i < v.size; i++) cout << v.vec[i] << " "; cout << endl; }
6.5
#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; for (int 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"); if (!out.is_open()) { cout << "fail to open file cipher_key.txt to write\n"; return 0; } output(out); out.close(); return 0; }