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;
}
相关推荐
superman超哥7 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q7 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
阿昭L7 小时前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹8 小时前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
liuyao_xianhui8 小时前
0~n-1中缺失的数字_优选算法(二分查找)
算法
hmbbcsm8 小时前
python做题小记(八)
开发语言·c++·算法
机器学习之心8 小时前
基于Stacking集成学习算法的数据回归预测(4种基学习器PLS、SVM、BP、RF,元学习器LSBoost)MATLAB代码
算法·回归·集成学习·stacking集成学习
图像生成小菜鸟8 小时前
Score Based diffusion model 数学推导
算法·机器学习·概率论
声声codeGrandMaster9 小时前
AI之模型提升
人工智能·pytorch·python·算法·ai
黄金小码农9 小时前
工具坐标系
算法