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;
}
相关推荐
C雨后彩虹8 分钟前
竖直四子棋
java·数据结构·算法·华为·面试
不如自挂东南吱1 小时前
空间相关性 和 怎么捕捉空间相关性
人工智能·深度学习·算法·机器学习·时序数据库
洛生&1 小时前
Elevator Rides
算法
2501_933513041 小时前
关于一种计数的讨论、ARC212C Solution
算法
Wu_Dylan1 小时前
智能体系列(二):规划(Planning):从 CoT、ToT 到动态采样与搜索
人工智能·算法
散峰而望1 小时前
【算法竞赛】栈和 stack
开发语言·数据结构·c++·算法·leetcode·github·推荐算法
知乎的哥廷根数学学派1 小时前
基于多尺度注意力机制融合连续小波变换与原型网络的滚动轴承小样本故障诊断方法(Pytorch)
网络·人工智能·pytorch·python·深度学习·算法·机器学习
蚊子码农2 小时前
算法题解记录-208实现Trie前缀树
运维·服务器·算法
2301_800256112 小时前
【人工智能引论期末复习】第3章 搜索求解2 - 对抗搜索
人工智能·算法·深度优先
程序猿阿伟2 小时前
《量子算法开发实战手册:Python全栈能力的落地指南》
python·算法·量子计算