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.mzph.cn/news/145416.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JVM虚拟机:垃圾回收器ZGC和Shenandoah算法

随着计算机技术的不断发展,内存管理成为了一个重要的话题。垃圾回收是一种自动内存管理技术,它可以自动地回收不再使用的内存,从而减少内存泄漏和程序崩溃的风险。在Java等高级编程语言中,垃圾回收器是必不可少的组件。近年来,ZGC和Shenandoah算法作为新一代的垃圾回收器,…

【ELK01】ELK简介以及ElasticSearch安装、ES客户端工具-Head安装、报错问题整理

有一段时间没有更新这个专栏了,最近在用ELK相关的技术,今天开始写一下ELK的系列的内容,与大家共同学习 一、什么是ELK ELK 是elastic公司提供的一套完整的日志收集以及展示的解决方案,是三个产品的首字母缩写,分别是ElasticSearch、Logstash 和 Kibana。 1. E-ELASTICS…

Linux实战一天一个小指令--《文件管理/文件查找》

阿丹&#xff1a; 作为一个java程序员进行实战开发不接触linux操作系统基本上是不可能的&#xff0c;所以这个专题就出现了&#xff0c;本文章重点解决大家关于文件管理以及文件查找查看的疑惑。我将采用语法基础用法并在下面进行高级语法的总结使用&#xff0c;方便大家学习和…

Python武器库开发-flask篇之URL重定向(二十三)

flask篇之URL重定向(二十三) 通过url_for()函数构造动态的URL&#xff1a; 我们在flask之中不仅仅是可以匹配静态的URL&#xff0c;还可以通过url_for()这个函数构造动态的URL from flask import Flask from flask import url_forapp Flask(__name__)app.route(/) def inde…

《硅基物语.AI写作高手:从零开始用ChatGPT学会写作》《从零开始读懂相对论》

文章目录 《硅基物语.AI写作高手&#xff1a;从零开始用ChatGPT学会写作》内容简介核心精华使用ChatGPT可以高效搞定写作的好处如下 《从零开始读懂相对论》内容简介关键点书摘最后 《硅基物语.AI写作高手&#xff1a;从零开始用ChatGPT学会写作》 内容简介 本书从写作与ChatG…

最新AI创作系统ChatGPT系统运营源码/支持最新GPT-4-Turbo模型/支持DALL-E3文生图

一、AI创作系统 SparkAi创作系统是基于OpenAI很火的ChatGPT进行开发的Ai智能问答系统和Midjourney绘画系统&#xff0c;支持OpenAI-GPT全模型国内AI全模型。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。那么如…

tcp的1对多模型C++处理逻辑

连接多个设备进行TCP连接,可以采取以下策略: 创建一个设备连接管理器:使用一个类或结构体来管理每个设备的连接。这个管理器应该包含设备的IP地址和端口号,以及一个连接到该设备的TCP连接。使用并发连接:使用并发的方式同时连接到所有设备。可以使用多线程或异步编程技术来…

R语言爬虫程序自动爬取图片并下载

R语言本身并不适合用来爬取数据&#xff0c;它更适合进行统计分析和数据可视化。而Python的requests&#xff0c;BeautifulSoup&#xff0c;Scrapy等库则更适合用来爬取网页数据。如果你想要在R中获取网页内容&#xff0c;你可以使用rvest包。 以下是一个简单的使用rvest包爬取…

云积万相,焕发电商店铺新活力

数字化时代&#xff0c;电商店铺的运营和营销策略越来越受到重视。如何让店铺在众多的竞争中脱颖而出&#xff0c;吸引更多的顾客&#xff0c;提高销售额&#xff0c;是每个电商品牌都需要思考的问题。云积天赫最近推出的云积万相为电商店铺带来全新的活力和更多的可能性。   …

promise时效架构升级方案的实施及落地 | 京东物流技术团队

一、项目背景 为什么需要架构升级 promise时效包含两个子系统&#xff1a;内核时效计算系统&#xff08;系统核心是时效计算&#xff09;和组件化时效系统&#xff08;系统核心是复杂业务处理以及多种时效业务聚合&#xff0c;承接结算下单黄金流程流量&#xff09;&#xff…

applicationContext.getBean 为null

场景&#xff1a; 使用SpringUtils 添加了统一类的调用。单元测试是正常的。 SpringUtils public class SpringUtils implements ApplicationContextAware {private static ApplicationContext applicationContext;Overridepublic void setApplicationContext(Nonnull Applica…

CNN(卷积神经网络)、RNN(循环神经网络)、DNN(深度神经网络)的内部网络结构有什么区别?

【导师不教&#xff1f;我来教&#xff01;】同济计算机博士半小时就教会了我五大深度神经网络&#xff0c;CNN/RNN/GAN/transformer/LSTM一次学会&#xff0c;简直不要太强&#xff01;_哔哩哔哩_bilibili了解的五大神经网络&#xff0c;整理笔记如下&#xff1a; 视频是唐宇…

【第2章 Node.js基础】2.7 Node.js 的流(一) 可读流

&#x1f308; Node.js 的流 &#x1f680;什么是流 流不是 Node.js 特有的概念。它们是几十年前在 Unix 操作系统中引入的。 我们可以把流看作这些数据的集合&#xff0c;就像液体一样&#xff0c;我们先把这些液体保存在一个容器里&#xff08;流的内部缓冲区 BufferList&…

JS原生-弹框+阿里巴巴矢量图

效果&#xff1a; 代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content&q…

【题解】洛谷 P9658 Laser Trap

题解-P9658 Laser Trap 题目传送门 题意简述 题面是英文的&#xff0c;还没翻译&#xff0c;就讲一讲吧。 n n n 个激光发射器&#xff0c;两两之间产生激光束&#xff0c;将平面分为若干区域。 问至少删去多少个发射器&#xff0c;可以使得原点与外侧区域联通。 多组数据&a…

Java封装一个根据指定的字段来获取子集的工具类

工具类 ZhLambdaUtils SuppressWarnings("all") public class ZhLambdaUtils {/*** METHOD_NAME*/private static final String METHOD_NAME "writeReplace";/*** 获取到lambda参数的方法名称** param <T> parameter* param function functi…

excel导入 Easy Excel

依旧是框架感觉有东西&#xff0c;但是确实是模拟不出来&#xff0c;各种零零散散的件太多了 controller层 ApiOperation(value "导入Excel", notes "导入Excel", httpMethod "POST", response ExcelResponseDTO.class)ApiImplicitParams({…

Unity3d 导入中文字体转TMPtext asset

外部字体放入unity仓库以后呢&#xff0c;需要把这个字体转成用立体的字体文件才可以被使用&#xff01; 要想转换的话呢先放入仓库对字体点右键上面有一个Create创建里面有一个TEXT Asset&#xff0c;创建好就可以使用了

(论文阅读32/100)Flowing convnets for human pose estimation in videos

32.文献阅读笔记 简介 题目 Flowing convnets for human pose estimation in videos 作者 Tomas Pfister, James Charles, and Andrew Zisserman, ICCV, 2015. 原文链接 https://arxiv.org/pdf/1506.02897.pdf 关键词 Human Pose Estimation in Videos 研究问题 视频…