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;
}
相关推荐
WBluuue10 小时前
Codeforces 1095 Div2(ABCDE)
c++·算法
IT当时语_青山师__JAVA技术栈10 小时前
数组与链表深度解析:从内存布局到工业级实践
java·算法·面试
吃着火锅x唱着歌10 小时前
LeetCode 496.下一个更大元素I
算法·leetcode·职场和发展
不知名的忻10 小时前
关键路径(Java)
java·数据结构·算法·关键路径
大大杰哥10 小时前
2025ccpc南昌补题笔记(前六题)
c++·笔记·算法
手写码匠10 小时前
手写 AI 智能路由系统:从零构建多模型调度与负载均衡
人工智能·深度学习·算法·aigc
sheeta199810 小时前
LeetCode 每日一题笔记 日期:2026.05.14 题目:2784. 检查数组是否是好的
笔记·算法·leetcode
故事还在继续吗10 小时前
DPDK 教程(三):多队列 + RSS + 多 worker 的最小转发 / Echo
算法·哈希算法·dpdk
AI科技星10 小时前
全域数学·体积与表面积通项定理【乖乖数学】
人工智能·算法·数学建模·数据挖掘·机器人
Yingjun Mo10 小时前
1. 在线学习引言
学习·算法