首页 > 编程语言 >三分钟读完《Essential C++》

三分钟读完《Essential C++》

时间:2023-09-12 18:12:48浏览次数:30  
标签:std int 三分钟 使用 C++ value 规则 include Essential

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <tuple>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>

#ifdef __cplusplus

#if __cplusplus <= 201103L
namespace std {
    template<typename T, typename... Args>
    std::unique_ptr<T> make_unique(Args&&... args) {
        return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
    }
}
#endif

#endif


// 规则1: 避免使用宏定义
// 不使用宏定义

// 规则2: 使用const来限制变量的修改
const int MAX_VALUE = 100;

// 规则3: 使用引用传递参数
void modifyValue(int& value) {
    value = 42;
}

// 规则4: 使用C++风格的类型转换
int intValue = static_cast<int>(3.14);

// 规则5: 使用const成员函数
class MyClass {
public:
    void modifyData() {
        data_ = 42;
    }

    int getData() const {
        return data_;
    }

private:
    int data_;
};

// 规则6: 尽量使用初始化列表
class AnotherClass {
public:
    AnotherClass(int value) : value_(value) {}

private:
    int value_;
};

// 规则7: 避免使用裸指针
std::unique_ptr<int> createIntPtr() {
    return std::make_unique<int>(42);
}

// 规则8: 使用std::string代替C风格字符串
std::string str = "Hello, world!";

// 规则9: 使用std::vector代替数组
std::vector<int> numbers = {1, 2, 3, 4, 5};

// 规则10: 使用std::array或std::vector代替C风格数组
std::array<int, 3> arr = {1, 2, 3};

// 规则11: 使用std::unique_ptr或std::shared_ptr管理动态内存
std::unique_ptr<int> ptr = std::make_unique<int>(42);

// 规则12: 使用范围for循环
void printNumbers(const std::vector<int>& nums) {
    for (const auto& num : nums) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

// 规则13: 避免使用goto语句
void someFunction() {
    bool condition = true;
    if (condition) {
        // do something
    } else {
        // do something else
    }
}

// 规则14: 使用自定义类型代替布尔型标志
enum class Status { OK, ERROR };

// 规则15: 将多个相关变量组织成结构体或类
struct Person {
    std::string name;
    int age;
};

// 规则16: 避免跨文件的全局变量
namespace {
    int internalVariable = 42;
}

// 规则17: 使用enum class代替enum
enum class Color { RED, GREEN, BLUE };

// 规则18: 将类的成员函数定义和声明分离
class MyClass2 {
public:
    void memberFunction(); // 在类的声明中只声明函数

private:
    int data_;
};

void MyClass2::memberFunction() {
    // 在类的定义中实现函数
}

// 规则19: 使用虚函数实现多态
class Base {
public:
    virtual void doSomething() {
        std::cout << "Base::doSomething()" << std::endl;
    }
};

class Derived : public Base {
public:
    void doSomething() override {
        std::cout << "Derived::doSomething()" << std::endl;
    }
};

// 规则20: 使用override关键字显式地重写虚函数
class Base2 {
public:
    virtual void doSomething() {
        std::cout << "Base2::doSomething()" << std::endl;
    }
};

class Derived2 : public Base2 {
public:
    void doSomething() override {
        std::cout << "Derived2::doSomething()" << std::endl;
    }
};

// 规则21: 使用final关键字禁止继承
class Base3 final {
public:
    virtual void doSomething() {
        std::cout << "Base3::doSomething()" << std::endl;
    }
};

// 规则22: 使用默认成员初始化
class MyClass3 {
public:
    MyClass3() = default; // 使用默认构造函数
    MyClass3(int value) : value_(value) {}

private:
    int value_ = 0; // 使用默认成员初始化
};

// 规则23: 使用std::initializer_list进行初始化
class MyClass4 {
public:
    MyClass4(std::initializer_list<int> values) {
        for (int value : values) {
            values_.push_back(value);
        }
    }

private:
    std::vector<int> values_;
};

// 规则24: 使用拷贝控制成员函数
class MyClass5 {
public:
    MyClass5(const MyClass5& other) {
        // 拷贝构造函数
    }

    MyClass5& operator=(const MyClass5& other) {
        if (this != &other) {
            // 拷贝赋值运算符
        }
        return *this;
    }

    ~MyClass5() {
        // 析构函数
    }
};

// 规则25: 使用移动语义提高性能
class MyClass6 {
public:
    MyClass6(MyClass6&& other) noexcept {
        // 移动构造函数
    }

    MyClass6& operator=(MyClass6&& other) noexcept {
        if (this != &other) {
            // 移动赋值运算符
        }
        return *this;
    }
};

// 规则26: 使用RAII资源管理
class File {
public:
    explicit File(const std::string& filename) {
        // 打开文件
    }

    ~File() {
        // 关闭文件
    }

    // 其他成员函数
};

// 规则27: 使用智能指针进行资源管理
void manageResource() {
    std::shared_ptr<int> ptr = std::make_shared<int>(42);
    // 使用智能指针ptr
}

// 规则28: 使用标准库容器进行数据管理
void manageData() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    // 使用numbers进行数据管理
}

// 规则29: 使用std::function实现函数对象
int add(int a, int b) {
    return a + b;
}

std::function<int(int, int)> func = add;

// 规则30: 使用Lambda表达式实现匿名函数
auto f30 = [](){
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int sum = 0;
    std::for_each(nums.begin(), nums.end(), [&](int num) {
        sum += num;
    });
};

// 规则31: 使用std::algorithm进行常见操作
std::vector<int> nums2 = {1, 2, 3, 4, 5};
int max = *std::max_element(nums2.begin(), nums2.end());

// 规则32: 使用异常处理错误
void process() {
    try {
        // 可能引发异常的代码
    } catch (const std::exception& e) {
        // 异常处理代码
    }
}

// 规则33: 使用异常规范声明函数可能抛出的异常
void func2() noexcept {
    // 不会抛出异常的函数
}

// 规则34: 使用std::mutex和std::lock_guard进行互斥访问
std::mutex mtx;
int sharedData = 0;

void updateSharedData() {
    std::lock_guard<std::mutex> lock(mtx);
    // 更新共享数据
}

// 规则35: 使用std::condition_variable进行线程同步
std::mutex mtx2;
std::condition_variable cv;
bool ready = false;

void waitForSignal() {
    std::unique_lock<std::mutex> lock(mtx2);
    cv.wait(lock, [] { return ready; });
    // 执行等待后的操作
}

void sendSignal() {
    std::lock_guard<std::mutex> lock(mtx2);
    ready = true;
    cv.notify_one();
}

// 规则36: 使用std::atomic进行原子操作
std::atomic<int> atomicValue{0};

void incrementAtomicValue() {
    atomicValue++;
}

// 规则37: 避免使用未定义行为
auto p37 = [](){
int x = 5;
int y = 0;
int result = x / y; // 未定义行为:除以0
};

// 规则38: 避免使用强制类型转换
double d = 3.14;
int i = static_cast<int>(d);

// 规则39: 使用命名空间进行组织和避免命名冲突
namespace MyNamespace {
    int value = 42;
}

// 规则40: 使用头文件保护
#ifndef MY_HEADER_H
#define MY_HEADER_H

// 头文件的内容

#endif

// 规则41: 避免滥用宏定义
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int maxValue = MAX(5, 10);

// 规则42: 使用迭代器进行数据遍历和操作
auto f42=[](){
    std::vector<int> numbers2 = {1, 2, 3, 4, 5};
    for (auto it = numbers2.begin(); it != numbers2.end(); ++it) {
        *it *= 2;
    }
};

// 规则43: 使用合适的容器选择算法
auto f43 = [](){
    std::vector<int> numbers3 = {1, 2, 3, 4, 5};
    std::sort(numbers3.begin(), numbers3.end());
};

// 规则44: 使用关联容器进行高效查找
auto f44 = [](){
std::map<std::string, int> scores = {{"Alice", 100}, {"Bob", 90}};
int aliceScore = scores["Alice"];
};

// 规则45: 使用std::tuple进行多值组合
std::tuple<std::string, int, double> data = std::make_tuple("Alice", 25, 3.14);
std::string name = std::get<0>(data);
int age = std::get<1>(data);
double value = std::get<2>(data);

// 规则46: 使用std::pair进行键值对存储
std::pair<std::string, int> student = {"Alice", 25};
std::string studentName = student.first;
int studentAge = student.second;

// 规则47: 使用std::set进行排序和去重
auto f47 = [](){
    std::set<int> uniqueNumbers = {2, 1, 3, 2, 4, 3, 5, 1};
    for (int num : uniqueNumbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
};

// 规则48: 使用std::map进行键值映射
std::map<std::string, int> ageMap = {{"Alice", 25}, {"Bob", 30}};
int aliceAge = ageMap["Alice"];

// 规则49: 使用std::unordered_set进行高效查找
std::unordered_set<int> numberSet = {1, 2, 3, 4, 5};
bool containsThree = numberSet.find(3) != numberSet.end();

// 规则50: 使用std::unordered_map进行高效键值映射
std::unordered_map<std::string, int> scoreMap = {{"Alice", 100}, {"Bob", 90}};
int aliceScore2 = scoreMap["Alice"];

// 规则51: 使用智能指针管理资源
std::shared_ptr<int> ptr2 = std::make_shared<int>(42);
// 使用智能指针ptr2

// 规则52: 使用std::reference_wrapper进行引用传递
void modifyValue(std::reference_wrapper<int> valueRef) {
    valueRef.get() = 42;
}

auto f52 = [](){
    int refValue = 10;
    modifyValue(refValue);
};

// 规则53: 使用std::tie进行元组解包
auto f53 = [](){
    std::tuple<std::string, int, double> studentData = std::make_tuple("Alice", 25, 3.14);
    std::string name2;
    int age2;
    double value2;
    std::tie(name2, age2, value2) = studentData;
};

// 规则54: 使用std::enable_if进行模板条件编译
template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type addOne(T value) {
    return value + 1;
}

// 规则55: 避免使用裸new和delete
std::unique_ptr<int> dynamicInt = std::make_unique<int>(42);

int main() {
    return 0;
}

标签:std,int,三分钟,使用,C++,value,规则,include,Essential
From: https://www.cnblogs.com/dujn/p/17697433.html

相关文章

  • bilibili B站:makefile 编译Linux C/C++项目快速入门
    视频摘自:https://www.bilibili.com/video/BV1vg41177zT    ......
  • C++模板介绍
    C++模板C++模板是一种强大的泛型编程工具,它允许我们编写通用的代码,可以用于处理多种不同的数据类型。模板允许我们在编写代码时将类型作为参数进行参数化,从而实现代码的重用性和灵活性。在C++中,模板由关键字template开始,并且后面跟着模板参数列表。模板参数可以是类型参数......
  • c++高精度模板
    #include<iostream>#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>#include<string>#include<vector>#include<list>usingnamespacestd;constintmaxn......
  • Qt/C++音视频开发52-采集本地屏幕桌面的终极设计
    一、前言最开始设计的时候,只考虑了一个屏幕的情况,这种当然是最理想的情况,实际上双屏或者多屏的用户也不在少数,比如我这两个屏幕,屏幕1是1080P,屏幕2是2K分辨率,打印两个屏幕的区域是QRect(0,01920x1030),QRect(1920,-2082560x1390),可以看到有个负数值(可以在操作系统中的排列显示......
  • C++算法之旅、06 基础篇 | 第四章 动态规划 详解
    常见问题闫式DP分析法状态表示集合满足一定条件的所有方案属性集合(所有方案)的某种属性(Max、Min、Count等)状态计算(集合划分)如何将当前集合划分成多个子集合状态计算相当于集合的划分:把当前集合划分成若干个子集,使得每个子集的状态可以先算出来,从而推导当前......
  • C++ Primer 第一章:一些尝试和认识
    Warning以下是一些非常无聊的知识点,附以肤浅的理解和解释,仅供参考,切勿轻信。C++Primer1.4.4示例代码PS:这段代码没什么用。#include<iostream>intmain(){ intcurrVal=0,val=0; //接收输入流的第一个数 if(std::cin>>currVal){ intcnt=1; //......
  • C++重载输入和输出运算符
    在C++中,标准库本身已经对左移运算符<<和右移运算符>>分别进行了重载,使其能够用于不同数据的输入输出,但是输入输出的对象只能是C++内置的数据类型(例如bool、int、double等)和标准库所包含的类类型(例如string、complex、ofstream、ifstream等)。如果我们自己定义了一种新的数据类......
  • C++ 优先队列 priority_queue
    既然是队列那么先要包含头文件#include<queue>,他和queue不同的就在于我们可以自定义其中数据的优先级,让优先级高的排在队列前面,优先出队优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的和队列基本操作相同:top访问队头......
  • C笔记--c++编译过程
    c++编译过程 参考资料:尚硅谷bilibili视频2023版......
  • C++ 围炉札记
    文章目录内存检测ProtoBufCMake、vscode、clion、Qt右值1、临时变量右值引用2、右值引用本质函数返回std::functionPOD(PlainOldData)thread_localnew/delete1、定位new运算符可变参数模板typename和class1、C++模板类头文件和实现文件分离的方法2、函数显示实例化3、类显示实例......