跳到主内容
C++
文章阅读

c++里面的标准库,信号,字符串操作,命名空间,map,set,模板引擎,异常处理,异步future等

2025/12/1679 次阅读11 分钟

cstdlib



#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
/**
 * 标准库操作
 */
int main() {


    //分配指定大小的内存
    int* ptr = (int*)malloc(10 * sizeof(int));
    cout << "ptr: " << ptr << endl;
    if (ptr == NULL) {
        cout << "分配内存失败了" << endl;
        exit(-1);
    }

    for (int i = 0; i < 10; i++) {
        ptr[i] = i * 1;//使用内存
    }
    for (int i = 0; i < 10; i++) {
        cout << "i=" << ptr[i] << endl;
    }

    //释放内存
    free(ptr);


    //atoi,atof 将字符串转数字和浮点数

    string a = "111";
    string b = "100.11";

    int aInt = atoi(a.c_str());
    double bDouble = atof(b.c_str());
    cout << "a=" << aInt << ",b=" << bDouble << endl;



    //rand,srand 函数
    srand(time(nullptr));
    for (int i = 0;i < 5;i++) {
        cout << rand() % 100 << " ";//0-99随机数
    }
    cout << endl;


    //执行一个命令行字符串
    system("kdoctor");

    //终止程序,返回状态码
    exit(0);

    return 0;
}

exception


#include <iostream>
#include <exception>
using namespace std;


double test(int a);
double test(int a) {
    if (a == 0) {
        throw "a不能等于0";
    }
    return a;
}


/**
 * 继承exception来定义新的异常
 * const throw: 异常规格说明,表名里面会抛出异常,不写可以抛出任何的异常
 */
struct MyException : public exception {
    const char* what() const throw () {
        return "发现梁典典异常";
    }
};



/**
 * 有三个关键字
 * try catch throw
 * throw: 有问题,通过它来抛出异常
 * catch: 捕获异常
 * try: 块中的代码被激活特定异常,后面可以跟随多个catch块
 */
int main() {
    try {
        test(1);
    }
    catch (const char* msg) {
        std::cout << msg << std::endl;
    }


    try {
        throw MyException();
    }
    catch (MyException& e) {
        cout << "进入自定义异常" << endl;
        cout << e.what() << endl;
    }
    catch (std::exception& e) {
        cout << "出现其他错误" << endl;
    }

    return 0;
}

future



#include <iostream>
#include <future>
using namespace std;

/**
 *  future: 异步操作的结果,支持查询操作的状态,读取结果,等待完成
 *  promise: 和future结合使用,设置异步操作的结果
 *  packaged_task: 封装函数和对象,使其可以异步任务执行
 */
int main() {

    promise<int> my_promise;
    future<int> wait_future = my_promise.get_future();

    // 使用 std::move 将 promise 移动到线程内部
    thread my_thread([p = std::move(my_promise)]() mutable {
        p.set_value(1);
        });

    cout << "结果: " << wait_future.get() << endl;

    my_thread.join();

    return 0;
}

map



#include <map>
#include <iostream>
using namespace std;

/**
 * 头文件: <map>
 * 1.map: 键值对,每个键都是唯一的
 * 2.元素都是按照键的顺序自动排序的,升序
 * 3.每个键只能出现一次
 * 4.提供了双向迭代器,支持向前,向后遍历元素
 */

int main() {

    map<string, int> devs;
    devs["c++"] = 1;
    devs["java"] = 2;
    devs["c"] = 3;
    devs["test"] = 4;


    //遍历
    for (std::map<string, int>::iterator it = devs.begin();it != devs.end();++it) {
        cout << it->first << " is " << it->second << "" << endl;
    }


    //检查键是否存在
    bool is_exit = devs.find("dev") != devs.end();
    if (is_exit) {
        cout << "已存在" << endl;
    }

    //删除元素
    int count = devs.erase("test");//返回1:成功,0不成功
    cout << "count is:" << count << endl;

    //获取大小
    int size = devs.size();
    cout << "map 的大小is:" << size << endl;

    //清空
    devs.clear();



    return 0;
}

namespace


#include <iostream>

using namespace std;
using std::cout;//某个函数,不需要namespace

namespace myfuns {
    void func() {
        cout << "my funs func" << std::endl;
    }
}

namespace tools {
    void func2() {
        cout << "my tool func" << std::endl;
    }
}


///还能有嵌套
namespace a {


    int a = 1;
    void funa() {
        cout << "a fun :" << a << endl;
    }
    namespace b {
        void bfun() {
            a = 10;
            cout << "b fun" << a << endl;
        }
    }
}

//使用using 告诉编译器,后面的代码使用指定的命名空间的名称
using namespace a::b;
using namespace tools;
int main() {


    //正常调用
    myfuns::func();
    tools::func2();
    func2();
    bfun();

    return 0;
}

set


#include <unordered_set>
#include <iostream>
using namespace std;
/**
 * unordered_set:存储唯一元素的集合,不保证元素排序,这点和set不同,可以用作更快的查找,插入,删除操作
 *
 */

int main() {

    unordered_set<int> my_set;

    my_set.insert(100);
    my_set.insert(200);
    my_set.insert(300);

    cout << "element is in my set";
    for (int ele : my_set) {
        cout << ele << " ";
    }

    cout << endl;


    ///查找元素
    auto it = my_set.find(100);
    if (it != my_set.end()) {
        cout << "找到了200元素" << endl;
    }
    else {
        cout << "200元素没有找到" << endl;
    }

    //删除元素
    int is_delete = my_set.erase(200);
    if (is_delete == 1) {
        cout << "删除成功" << endl;
    }
    else {
        cout << "删除失败了" << endl;
    }

    //获取大小和检查是否为空
    int size = my_set.size();
    bool is_empty = my_set.empty();

    cout << "大小:" << size << ",是否为空" << is_empty << endl;


    //清空
    my_set.clear();

    cout << "是否为空?" << (my_set.empty() ? "yes" : "no") << endl;
    return 0;
}

singnal


#include <iostream>
#include <csignal>
#include <unistd.h>
using namespace std;



void mySingnalHandle(int  signum) {
    cout << "中断信号:" << signum << endl;
    exit(signum);
}

/**
 * 使用raise来生成信号
 */
void mySingalHanlde2(int signum) {
    cout << "2.中断信号:" << signum << endl;
    exit(signum);
}





/**
 * 信号处理
 */
int main() {

    ///注册信号
    signal(5, mySingalHanlde2);
    // while (1)
    // {
    //     cout << "睡眠..." << endl;
    //     sleep(1);
    // }

    int i = 1;

    while (++i)
    {
        cout << "睡眠" << endl;
        if (i == 5) {
            raise(i);
        }
        sleep(1);
    }


    return 0;
}

template


#include <iostream>
#include <string>
#include <vector>
using namespace std;

/**
 * 函数模板
 * template <typename type> return-type func-name(parameter list)
 */
template <typename T>
inline T const& Max(T const& a, T const& b) {
    return a < b ? b : a;
}

/**
 * 类模板
 * template <class type> class class-name{}
 */

template <class T>
class Stack {
private:
    vector<T> elems; //元素列表
public:
    void push(T const&);//入
    void pop(); //出
    T top() const; //顶部元素
    bool empyu() const {
        return elems.empty();
    }
};

template <class T>
void Stack<T>::push(T const& elem) {
    this->elems.push_back(elem);
}

template <class T>
void Stack<T>::pop() {
    if (elems.empty()) {
        throw out_of_range("Stack<>::pop:empty stack");
    }
    //删除最后一个元素
    this->elems.pop_back();
}

template <class T>
T Stack<T>::top() const {
    if (this->elems.empty()) {
        throw out_of_range("Stack<>::pop:empty stack");
    }
    return this->elems.back();//返回最后一个元素
}





int main() {


    int a = 1;
    int b = 2;
    cout << "Max(a,b)" << Max(a, b) << endl;

    int a2 = 12.4;
    int b2 = 99.0;
    cout << "Max(a2,b2)" << Max(a2, b2) << endl;


    string a3 = "dasdas";
    string b3 = "tetesgf";

    cout << "Max(a3,b3)" << Max(a3, b3) << endl;


    try {

        Stack<int> int_stack;
        Stack<string> string_stack;

        int_stack.push(1);

        cout << int_stack.top() << endl;

        string_stack.push("梁典典");
        cout << string_stack.top() << endl;

        string_stack.pop();
        string_stack.pop();
    }
    catch (exception const& ex) {
        cerr << "exception is " << ex.what() << endl;
        return -1;
    }

    return 0;
}
返回顶部