当前位置: 首页 > news >正文

C++面试常考手写题目

C++面试常考手写题目

  • vector
  • string
  • auto_ptr
  • shared_ptr
  • unique_ptr
  • weak_ptr
  • singleton
  • 快排非递归
  • heap
  • heap_sort
  • merge_sort

vector

#include <bits/stdc++.h>
using namespace std;template<typename T>
class vector {public:typedef T value_type;typedef T* iterator;private:value_type* _data;size_t _size;size_t _capacity;public:vector(): _data(NULL), _size(0), _capacity(0) {}~vector() {delete [] _data;_data = NULL;_size = 0;_capacity = 0;}vector(const vector& vec) {_size = vec._size;_capacity = vec._capacity;_data = new value_type[_capacity];for (int i = 0; i < _size; ++i) {_data[i] = vec._data[i];}}vector& operator=(const vector& vec) {if (this == &vec) return *this;value_type* temp = new value_type[vec._capacity];for (int i = 0; i < vec._size; ++i) {temp[i] = vec._data[i];}delete [] _data;_data = temp;_size = vec._size;_capacity = vec._capacity;return *this;}void push_back(value_type val) {if (0 == _capacity) {_capacity = 1;_data = new value_type[1];} else if (_size + 1 > _capacity) {_capacity *= 2;value_type* temp = new value_type[_capacity];for (int i = 0; i < _size; ++i) {temp[i] = _data[i];}delete [] _data;_data = temp;}_data[_size] = val;++_size;}void pop_back() {--_size;}size_t size() const {return _size;}size_t capacity() const {return _capacity;}bool empty() {return _size == 0;}value_type& operator[](size_t index) {return _data[index];}bool operator==(const vector& vec)const {if (_size != vec._size) return false;for (int i = 0; i < _size; ++i) {if (_data[i] != vec._data[i]) return false;}return true;}value_type front()const {return _data[0];}value_type back() const {return _data[_size - 1];}void insert(iterator it, value_type val) {int index = it - _data;if (0 == _capacity) {_capacity = 1;_data = new value_type[1];_data[0] = val;} else if (_size + 1 > _capacity) {_capacity *= 2;value_type* temp = new value_type[_capacity];for (int i = 0; i < index; ++i) {temp[i] = _data[i];}temp[index] = val;for (int i = index; i < _size; ++i) {temp[i + 1] = _data[i];}delete [] _data;_data = temp;} else {for (int i = _size - 1; i >= index; --i) {_data[i + 1] = _data[i];}_data[index] = val;}++_size;}void erase(iterator it) {size_t index = it - _data;for (int i = index; i < _size - 1; ++i) {_data[i] = _data[i + 1];}--_size;}iterator begin() {return _data;}iterator end() {return _data + _size;}
};

string

#include <iostream>
#include <cstring>class MyString {
public:// 构造函数MyString() {data_ = new char[1];data_[0] = '\0';size_ = 0;}MyString(const char* str) {size_ = strlen(str);data_ = new char[size_ + 1];strcpy(data_, str);}// 拷贝构造函数MyString(const MyString& other) {size_ = other.size_;data_ = new char[size_ + 1];strcpy(data_, other.data_);}// 析构函数~MyString() {delete[] data_;}// 赋值运算符MyString& operator=(const MyString& other) {if (this == &other) {return *this;}delete[] data_;size_ = other.size_;data_ = new char[size_ + 1];strcpy(data_, other.data_);return *this;}// 大小size_t size() const {return size_;}// 清空void clear() {delete[] data_;data_ = new char[1];data_[0] = '\0';size_ = 0;}// 字符串内容的访问const char* c_str() const {return data_;}private:char* data_;size_t size_;
};

auto_ptr

#include <bits/stdc++.h>
using namespace std;template<class T>
class auto_ptr {public:auto_ptr(T* ptr = nullptr) : _ptr(ptr) {}~auto_ptr() {if (_ptr != nullptr) {cout << "delete: " << _ptr << endl;delete _ptr;_ptr = nullptr;}}auto_ptr(auto_ptr<T>& ap): _ptr(ap._ptr) {ap._ptr = nullptr; // 管理权转移后ap被置空}auto_ptr& operator=(auto_ptr<T>& ap) {if (this != &ap) {delete _ptr;       // 释放自己管理的资源_ptr = ap._ptr;    // 接管ap对象的资源ap._ptr = nullptr; // 管理权转移后ap被置空}return *this;}// 可以像指针一样使用T& operator*() {return *_ptr;}T* operator->() {return _ptr;}private:T* _ptr; //管理的资源
};

shared_ptr

#include <bits/stdc++.h>
using namespace std;template<class T>
class shared_ptr {public:shared_ptr(T* ptr = nullptr): _ptr(ptr), _pcount(new int(1)){}shared_ptr(shared_ptr<T>& sp): _ptr(sp._ptr), _pcount(sp._pcount) {(*_pcount)++;}~shared_ptr() {if (--(*_pcount) == 0) {if (_ptr != nullptr) {cout << "delete: " << _ptr << endl;delete _ptr;_ptr = nullptr;}delete _pcount;_pcount = nullptr;}}shared_ptr& operator=(shared_ptr<T>& sp) {if (_ptr != sp._ptr) { // 管理同一块空间的对象之间无需进行赋值操作if (--(*_pcount) == 0) { // 将管理的资源对应的引用计数--cout << "delete: " << _ptr << endl;delete _ptr;delete _pcount;}_ptr = sp._ptr;       // 与sp对象一同管理它的资源_pcount = sp._pcount; // 获取sp对象管理的资源对应的引用计数(*_pcount)++;         // 新增一个对象来管理该资源 引用计数++}return *this;}// 获取引用计数int use_count() {return *_pcount;}// 可以像指针一样使用T& operator*() {return *_ptr;}T* operator->() {return _ptr;}private:T* _ptr;      // 管理的资源int* _pcount; // 管理的资源对应的引用计数 堆上
};template<class T>
class shared_ptr_with_mutex {private:// ++引用计数void AddRef() {_pmutex->lock();(*_pcount)++;_pmutex->unlock();}// --引用计数void ReleaseRef() {_pmutex->lock();bool flag = false;if (--(*_pcount) == 0) { // 将管理的资源对应的引用计数--if (_ptr != nullptr) {cout << "delete: " << _ptr << endl;delete _ptr;_ptr = nullptr;}delete _pcount;_pcount = nullptr;flag = true;}_pmutex->unlock();if (flag == true) {delete _pmutex;}}public:shared_ptr_with_mutex(T* ptr = nullptr): _ptr(ptr), _pcount(new int(1)), _pmutex(new mutex){}shared_ptr_with_mutex(shared_ptr_with_mutex<T>& sp): _ptr(sp._ptr), _pcount(sp._pcount), _pmutex(sp._pmutex) {AddRef();}~shared_ptr_with_mutex() {ReleaseRef();}shared_ptr_with_mutex& operator=(shared_ptr_with_mutex<T>& sp) {if (_ptr != sp._ptr) { // 管理同一块空间的对象之间无需进行赋值操作ReleaseRef();         // 将管理的资源对应的引用计数--_ptr = sp._ptr;       // 与sp对象一同管理它的资源_pcount = sp._pcount; // 获取sp对象管理的资源对应的引用计数_pmutex = sp._pmutex; // 获取sp对象管理的资源对应的互斥锁AddRef();             // 新增一个对象来管理该资源,引用计数++}return *this;}// 获取引用计数int use_count() {return *_pcount;}// 可以像指针一样使用T& operator*() {return *_ptr;}T* operator->() {return _ptr;}private:T* _ptr;        // 管理的资源int* _pcount;   // 管理的资源对应的引用计数mutex* _pmutex; // 管理的资源对应的互斥锁
};

unique_ptr

#include <bits/stdc++.h>
using namespace std;template<class T>
class unique_ptr {public:unique_ptr(T* ptr = nullptr): _ptr(ptr){}~unique_ptr() {if (_ptr != nullptr) {cout << "delete: " << _ptr << endl;delete _ptr;_ptr = nullptr;}}// 可以像指针一样使用T& operator*() {return *_ptr;}T* operator->() {return _ptr;}// 防拷贝unique_ptr(unique_ptr<T>& up) = delete;unique_ptr& operator=(unique_ptr<T>& up) = delete;private:T* _ptr; // 管理的资源
};

weak_ptr

#include <bits/stdc++.h>
using namespace std;template<class T>
class weak_ptr {public:weak_ptr(): _ptr(nullptr){}weak_ptr(const shared_ptr<T>& sp): _ptr(sp.get()){}weak_ptr& operator=(const shared_ptr<T>& sp) {_ptr = sp.get();return *this;}// 可以像指针一样使用T& operator*() {return *_ptr;}T* operator->() {return _ptr;}private:T* _ptr; // 管理的资源
};

singleton

#include <iostream>
#include <mutex>class Singleton {
private:static Singleton* instance;static std::mutex mtx;Singleton() {}  // 私有构造函数,防止外部实例化public:static Singleton* getInstance() {if (instance == nullptr) {std::lock_guard<std::mutex> lock(mtx);  // 加锁if (instance == nullptr) {instance = new Singleton();}}return instance;}void showMessage() {std::cout << "Hello, I am a singleton instance!" << std::endl;}
};Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;int main() {Singleton* singleton1 = Singleton::getInstance();singleton1->showMessage();Singleton* singleton2 = Singleton::getInstance();singleton2->showMessage();return 0;
}

快排非递归

#include <bits/stdc++.h>
using namespace std;用一个栈(std::stack)将以下用递归实现的快排函数改成非递归// usage://std::vector<int> v = {3, 2, 1, 5, 6, 9, -1, -2, 0};//QuickSort(&v[0], 0, int(v.size())-1);void QuickSort(int *array, int low, int high){int i = low;int j = high;int pivot = array[(i + j) / 2];while (i <= j){while (array[i] < pivot)++i;while (array[j] > pivot)--j;if (i <= j){std::swap(array[i], array[j]);++i;--j;}}if (j > low)QuickSort(array, low, j);if (i < high)QuickSort(array, i, high);}void QuickSort(int* array, int low, int high) {stack<pair<int, int>> mystack;mystack.push(make_pair(low, high));while (!mystack.empty()) {int _low = mystack.top().first;int _high = mystack.top().second;int i = _low;int j = _high;mystack.pop();int pivot = array[(i + j) / 2];while (i <= j) {while (array[i] < pivot)++i;while (array[j] > pivot)--j;if (i <= j) {std::swap(array[i], array[j]);++i;--j;}}if (j > _low)mystack.push(make_pair(_low, j));if (i < _high)mystack.push(make_pair(i, _high));}
}
void display(vector<int>& a) {for (int& e : a) {cout << e << " ";}cout << endl;
}

heap

#include <iostream>
#include <vector>// 最小堆
class MinHeap {
public:MinHeap() {}void insert(int value) {heap.push_back(value);heapifyUp(heap.size() - 1);}int pop() {if (heap.empty()) {throw std::out_of_range("Heap is empty");}int minValue = heap[0];heap[0] = heap.back();heap.pop_back();heapifyDown(0);return minValue;}bool isEmpty() const {return heap.empty();}private:std::vector<int> heap;void heapifyUp(int index) {int parent = (index - 1) / 2;while (index > 0 && heap[index] < heap[parent]) {std::swap(heap[index], heap[parent]);index = parent;parent = (index - 1) / 2;}}void heapifyDown(int index) {int leftChild = 2 * index + 1;int rightChild = 2 * index + 2;int smallest = index;if (leftChild < heap.size() && heap[leftChild] < heap[smallest]) {smallest = leftChild;}if (rightChild < heap.size() && heap[rightChild] < heap[smallest]) {smallest = rightChild;}if (smallest != index) {std::swap(heap[index], heap[smallest]);heapifyDown(smallest);}}
};int main() {MinHeap heap;heap.insert(10);heap.insert(5);heap.insert(15);heap.insert(20);heap.insert(3);while (!heap.isEmpty()) {std::cout << heap.pop() << " ";}std::cout << std::endl;return 0;
}

heap_sort

#include <iostream>
#include <vector>void heapify(std::vector<int>& arr, int n, int i) {int largest = i;int left = 2 * i + 1;int right = 2 * i + 2;if (left < n && arr[left] > arr[largest]) {largest = left;}if (right < n && arr[right] > arr[largest]) {largest = right;}if (largest != i) {std::swap(arr[i], arr[largest]);heapify(arr, n, largest);}
}void heapSort(std::vector<int>& arr) {int n = arr.size();// 构建最大堆for (int i = n / 2 - 1; i >= 0; i--) {heapify(arr, n, i);}// 逐个提取最大元素并调整堆for (int i = n - 1; i > 0; i--) {std::swap(arr[0], arr[i]);heapify(arr, i, 0);}
}int main() {std::vector<int> arr = {9, 4, 7, 2, 1, 5, 8, 3, 6};heapSort(arr);std::cout << "排序结果: ";for (int num : arr) {std::cout << num << " ";}std::cout << std::endl;return 0;
}

merge_sort

#include <iostream>
#include <vector>// 合并两个有序数组
void merge(std::vector<int>& arr, int left, int mid, int right) {int n1 = mid - left + 1;int n2 = right - mid;std::vector<int> leftArr(n1);std::vector<int> rightArr(n2);for (int i = 0; i < n1; i++) {leftArr[i] = arr[left + i];}for (int j = 0; j < n2; j++) {rightArr[j] = arr[mid + 1 + j];}int i = 0, j = 0, k = left;while (i < n1 && j < n2) {if (leftArr[i] <= rightArr[j]) {arr[k] = leftArr[i];i++;} else {arr[k] = rightArr[j];j++;}k++;}while (i < n1) {arr[k] = leftArr[i];i++;k++;}while (j < n2) {arr[k] = rightArr[j];j++;k++;}
}// 递归实现归并排序
void mergeSortRecursive(std::vector<int>& arr, int left, int right) {if (left < right) {int mid = left + (right - left) / 2;mergeSortRecursive(arr, left, mid);mergeSortRecursive(arr, mid + 1, right);merge(arr, left, mid, right);}
}// 非递归实现归并排序
void mergeSortIterative(std::vector<int>& arr) {int n = arr.size();int currSize;for (currSize = 1; currSize <= n - 1; currSize = 2 * currSize) {for (int left = 0; left < n - 1; left += 2 * currSize) {int mid = std::min(left + currSize - 1, n - 1);int right = std::min(left + 2 * currSize - 1, n - 1);merge(arr, left, mid, right);}}
}int main() {std::vector<int> arr = {9, 4, 7, 2, 1, 5, 8, 3, 6};std::cout << "递归归并排序结果: ";mergeSortRecursive(arr, 0, arr.size() - 1);for (int num : arr) {std::cout << num << " ";}std::cout << std::endl;std::vector<int> arr2 = {9, 4, 7, 2, 1, 5, 8, 3, 6};std::cout << "非递归归并排序结果: ";mergeSortIterative(arr2);for (int num : arr2) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
http://www.lryc.cn/news/233251.html

相关文章:

  • LLM建模了什么,为什么需要RAG
  • 为开发GPT-5,OpenAI向微软寻求新融资
  • 创邻科技亮相ISWC 2023,国际舞台见证知识图谱领域研究突破
  • 开源博客项目Blog .NET Core源码学习(6:雪花算法)
  • 【Python】集合与字典
  • 【LeetCode】88. 合并两个有序数组
  • Linux文件权限
  • 〖大前端 - 基础入门三大核心之JS篇㉟〗- JavaScript 的DOM简介
  • CentOS中安装常用环境
  • python时间变化与字符串替换技术及读JSON文件等实践笔记
  • leetcode刷题日记:141. Linked List Cycle(环形链表)
  • html书本翻页效果,浪漫表白日记本(附源码)
  • 【Mysql】学习笔记
  • 工作记录-------java文件的JVM之旅(学习篇)---好理解
  • 城市内涝对策,万宾科技内涝积水监测仪使用效果
  • android的通知使用
  • 001 opencv addWeighted
  • 2311rust,到35版本更新
  • UniPro提高集成能力 让客户专注于交付价值
  • Python---函数的作用,定义,使用步骤(调用步骤)
  • ERP智能管理系统:智能化的未来之路
  • c++ memccpy和 = 都可以用于赋值操作
  • Golang for 循环中的隐式内存别名问题
  • 2023年亚太杯数学建模思路 - 复盘:光照强度计算的优化模型
  • Unity——利用Mesh绘制图形
  • web3资讯及远程工作
  • 契约锁助力货物进出口全程无纸化,加速通关、降低贸易成本
  • 生活中的综合能力
  • ES5中实现继承
  • 面试鸭 - 专注于面试刷题的网站