代码面试C++/STL Cheat Sheet
在以前的面试指南中,写代码不限定编程语言,主要考察算法。近几年机器学习火了之后,作为面试官,面试科班出身的面试者我会要求对方使用C或C++而非Python。原因很简单,现在许多科班出身的同学基本功不扎实,恨不能大一上来就搞深度学习,对计算机科学没有大局观和底层的认识,往往不能很好地胜任日常的工作。而C/C++作为科班的必修课,可以作为一个简单的分类器判断对方的功底。
吐槽完毕,LeetCode是大家常用来刷题的网站,但对于工作中不把C/C++作为开发语言的工程师来说有些语法太久不用就忘了,更不提STL中的一些特殊数据结构的方法,这里简单总结一下,便于快速捡起来。
#include <iostream> #include <climits> #include <vector> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> #include <deque> using namespace std; int main() { // Constants cout<<"INT_MAX: "<<INT_MAX<<endl; cout<<"INT_MIN: "<<INT_MIN<<endl; // Vector vector<int> v(3, 0); // Init a 1 * 3 vector with value 0 v.push_back(0); v.pop_back(); cout<<"Final vector size: "<<v.size()<<endl; vector<vector<int>> v2d(3, vector<int>(5, 0)); // Init a 3 * 5 2d vector with value 0 cout<<"2d vector size: "<<v2d.size()<<" * "<<v2d[0].size()<<endl; // Map & unordered_map unordered_map<int, int> m; m[0] = 1; m.erase(0); cout<<"Final map size: "<<m.size()<<endl; // Set & unordered_set unordered_set<int> s; s.insert(0); s.erase(0); cout<<"Final set size: "<<s.size()<<endl; // Stack stack<int> stk; stk.push(0); int stackTop = stk.top(); stk.pop(); cout<<"Final stack size: "<<stk.size()<<endl; // Queue queue<int> q; q.push(0); int qFront = q.front(); q.pop(); cout<<"Final queue size: "<<q.size()<<endl; // Deque deque<int> deq; deq.push_front(0); deq.push_back(1); int deqFront = deq.front(); int deqBack = deq.back(); cout<<"Deque: "<<deqFront<<" "<<deqBack<<endl; deq.pop_front(); deq.pop_back(); cout<<"Final deque size: "<<deq.size()<<endl; // Priority Queue priority_queue<int> pq; // max heap pq.push(0); pq.push(1); int pqTop = pq.top(); cout<<"Priority queue top: "<<pqTop<<endl; pq.pop(); cout<<"Final priority queue size: "<<pq.size()<<endl; }
运行结果:
INT_MAX: 2147483647 INT_MIN: -2147483648 Final vector size: 3 2d vector size: 3 * 5 Final map size: 0 Final set size: 0 Final stack size: 0 Final queue size: 0 Deque: 0 1 Final deque size: 0 Priority queue top: 1 Final priority queue size: 1
Preview: