C++面试常考手写题目

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值