C++ 面试问题集合

文章目录

设计模式

单例

cpp 复制代码
#include <iostream>
#include <string>
#include <memory>
#include <mutex>
#include <thread>

using namespace std;

class SingleTon{
protected:
    //外部不可直接操作
    SingleTon(const string& value):_value(value) {
        cout<< "SingleTon Construct" <<endl;
    }
    
    ~SingleTon() {
        cout<< "SingleTon Destruct" <<endl;
    }
    
    //静态成员   全局访问  智能指针   自动释放
    static  shared_ptr<SingleTon> singleton;
    
    string _value;
    
public:
    //禁止外部移动和拷贝
    SingleTon(const SingleTon && obj) = delete;
    void operator=(const SingleTon  obj) = delete;
    
    //提供静态接口  类名调用
    static shared_ptr<SingleTon> getInstance(const string& value){
        //call once 调用
        static once_flag s_flag;
        call_once(s_flag , [&](){ 
            singleton = shared_ptr<SingleTon>(new SingleTon(value), [](SingleTon * singleton){ delete singleton;});
        });
        
        return singleton;
    }
    
    string pinrtValue(){
        return _value;
    }
};

//变量重置
shared_ptr<SingleTon> SingleTon::singleton = nullptr;

void printValue(const string & value){
    cout<< SingleTon::getInstance(value)->pinrtValue()<<endl;
}

int main(){
    thread th1(printValue,"aaa");
    thread th2(printValue,"bbb");
    
    th1.join();
    th2.join();
    
    return 0;
}

排序算法

查找算法

二分查找

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

using Rank = int;

class Fib{
private:
    Rank g ,f;
    
public:
    Fib(Rank n){
        f =0; g= 1;  //f 代表 fib(k -1)  g 代表 fib(k)
        while(0 < n--){
            g = g + f;
            f = g - f;
        }
    }
    
    Rank get(){return g;}
    
    Rank next(){
        g = g + f;
        f = g -f;
        
        return g;
    };
    
    Rank pre(){
        f = g-f;
        g = g-f;
        
        return g;
    }
};

template < typename T>
static Rank fibSearch(T *A,const T &e,Rank lo,Rank hi){
    for(Fib fib(hi - lo) ; lo < hi;){
        while( hi -lo < fib.get()) fib.pre();
        
        Rank mi = lo + fib.get() -1;
        
        (e < A[mi]) ? hi = mi : lo = mi + 1;
    }
    
    return lo - 1;
}

int main(){
    std::vector<Rank> test{1,3,6,8,9,11,13,17,20} ;
    
    Rank index = fibSearch<Rank>(test.data(),14,0,test.size());
    
    cout << "index: " << index <<endl;
    
    return 0;
}
相关推荐
Flash.kkl17 分钟前
优先算法——专题十一:字符串
算法
汉克老师7 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh8 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
c++bug8 小时前
六级第一关——下楼梯
算法
Morri38 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛9 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
AndrewHZ9 小时前
【3D算法技术】blender中,在曲面上如何进行贴图?
算法·3d·blender·贴图·三维建模·三维重建·pcg
Jared_devin9 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯
AI 嗯啦10 小时前
数据结构深度解析:二叉树的基本原理
数据结构·算法
和光同尘@11 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展