基于C Plus Plus的数据结构与算法课程 首套C++完美结合的数据结构与算法

dfdggd · · 58 次点击 · · 开始浏览    

  获课♥》789it.top/14147/

C++与数据结构:构建高性能应用程序的基础

C++作为高性能编程语言的优势

C++因其独特的特性成为构建高性能应用程序的首选语言:

  1. 零成本抽象:高级特性如类、模板几乎不带来运行时开销

  2. 内存控制:直接内存访问和精细的内存管理能力

  3. 多范式支持:支持面向对象、泛型和过程式编程

  4. 硬件访问:内联汇编和与C的兼容性允许底层硬件操作

  5. 标准库丰富:提供STL等高效的数据结构和算法实现

基础数据结构及其C++实现

数组与向量

cpp

复制

下载

// 原始数组
int arr[5] = {1, 2, 3, 4, 5};

// std::array (C++11)
std::array<int, 5> stdArr = {1, 2, 3, 4, 5};

// std::vector (动态数组)
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);  // 动态扩展

链表结构

cpp

复制

下载

// 单向链表节点
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

// std::forward_list (C++11单向链表)
std::forward_list<int> flist = {1, 2, 3};

// std::list (双向链表)
std::list<int> dlist = {4, 5, 6};
dlist.push_front(3);
dlist.push_back(7);

栈与队列

cpp

复制

下载

// 栈
std::stack<int> s;
s.push(1);
s.push(2);
int top = s.top();  // 2
s.pop();

// 队列
std::queue<int> q;
q.push(1);
q.push(2);
int front = q.front();  // 1
q.pop();

// 优先队列(堆)
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(4);
int top = pq.top();  // 4

哈希表

cpp

复制

下载

// std::unordered_map (哈希表)
std::unordered_map<std::string, int> wordCount;
wordCount["hello"] = 1;
wordCount["world"] = 2;

// std::unordered_set (哈希集合)
std::unordered_set<int> uniqueNumbers;
uniqueNumbers.insert(1);
uniqueNumbers.insert(2);

高级数据结构实现

二叉搜索树

cpp

复制

下载

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class BST {
private:
    TreeNode* root;
    
    TreeNode* insert(TreeNode* node, int val) {
        if (!node) return new TreeNode(val);
        if (val < node->val) node->left = insert(node->left, val);
        else node->right = insert(node->right, val);
        return node;
    }
    
public:
    BST() : root(nullptr) {}
    
    void insert(int val) {
        root = insert(root, val);
    }
    
    // 其他操作...
};

图结构

cpp

复制

下载

// 邻接表表示
class Graph {
private:
    int V; // 顶点数
    std::vector<std::list<int>> adj;

public:
    Graph(int V) : V(V), adj(V) {}
    
    void addEdge(int v, int w) {
        adj[v].push_back(w);
    }
    
    void BFS(int s) {
        std::vector<bool> visited(V, false);
        std::queue<int> q;
        
        visited[s] = true;
        q.push(s);
        
        while (!q.empty()) {
            s = q.front();
            q.pop();
            
            for (auto i = adj[s].begin(); i != adj[s].end(); ++i) {
                if (!visited[*i]) {
                    visited[*i] = true;
                    q.push(*i);
                }
            }
        }
    }
};

性能优化技巧

  1. 内存局部性优化

    • 使用连续内存结构(如vector)替代链表

    • 预分配内存避免频繁重新分配

  2. 算法选择

    • 根据数据规模选择O(1)、O(log n)或O(n)算法

    • 权衡时间与空间复杂度

  3. 缓存友好设计

    • 结构体大小对齐

    • 避免随机内存访问模式

  4. 移动语义(C++11)

    cpp

    复制

    下载

    std::vector<int> createLargeVector() {
        std::vector<int> v(1000000);
        // 填充数据...
        return v;  // 使用移动而非复制
    }
  5. 智能指针管理内存

    cpp

    复制

    下载

    std::shared_ptr<Node> node = std::make_shared<Node>(42);
    std::unique_ptr<Node> uniqueNode = std::make_unique<Node>(24);

实际应用案例

高性能缓存实现

cpp

复制

下载

template<typename K, typename V>
class LRUCache {
private:
    using ListType = std::list<std::pair<K, V>>;
    using MapType = std::unordered_map<K, typename ListType::iterator>;
    
    ListType cacheList;
    MapType cacheMap;
    size_t capacity;
    
public:
    LRUCache(size_t capacity) : capacity(capacity) {}
    
    V get(K key) {
        auto it = cacheMap.find(key);
        if (it == cacheMap.end()) return V();
        
        // 移动到列表前端
        cacheList.splice(cacheList.begin(), cacheList, it->second);
        return it->second->second;
    }
    
    void put(K key, V value) {
        auto it = cacheMap.find(key);
        if (it != cacheMap.end()) {
            it->second->second = value;
            cacheList.splice(cacheList.begin(), cacheList, it->second);
            return;
        }
        
        if (cacheMap.size() >= capacity) {
            // 移除最久未使用的
            K lastKey = cacheList.back().first;
            cacheMap.erase(lastKey);
            cacheList.pop_back();
        }
        
        cacheList.emplace_front(key, value);
        cacheMap[key] = cacheList.begin();
    }
};

并发数据结构

cpp

复制

下载

#include <mutex>
#include <condition_variable>

template<typename T>
class ThreadSafeQueue {
private:
    std::queue<T> queue;
    mutable std::mutex mtx;
    std::condition_variable cv;
    
public:
    void push(T value) {
        std::lock_guard<std::mutex> lock(mtx);
        queue.push(std::move(value));
        cv.notify_one();
    }
    
    bool try_pop(T& value) {
        std::lock_guard<std::mutex> lock(mtx);
        if (queue.empty()) return false;
        
        value = std::move(queue.front());
        queue.pop();
        return true;
    }
    
    void wait_and_pop(T& value) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [this]{ return !queue.empty(); });
        
        value = std::move(queue.front());
        queue.pop();
    }
};

现代C++特性应用

使用模板元编程优化

cpp

复制

下载

template<typename T, size_t BlockSize = 4096 / sizeof(T)>
class MemoryPool {
private:
    struct Block {
        T data[BlockSize];
        Block* next;
    };
    
    Block* currentBlock = nullptr;
    size_t currentPosition = 0;
    
public:
    T* allocate() {
        if (!currentBlock || currentPosition >= BlockSize) {
            currentBlock = new Block{ {}, currentBlock };
            currentPosition = 0;
        }
        return &currentBlock->data[currentPosition++];
    }
    
    ~MemoryPool() {
        while (currentBlock) {
            Block* next = currentBlock->next;
            delete currentBlock;
            currentBlock = next;
        }
    }
};

使用Lambda和算法

cpp

复制

下载

void processData(std::vector<int>& data) {
    // 并行排序 (C++17)
    std::sort(std::execution::par, data.begin(), data.end());
    
    // 使用lambda过滤
    data.erase(std::remove_if(data.begin(), data.end(), 
        [](int x) { return x % 2 == 0; }), data.end());
    
    // 变换操作
    std::transform(data.begin(), data.end(), data.begin(),
        [](int x) { return x * x; });
}

总结

C++与数据结构的结合为构建高性能应用程序提供了坚实基础。通过:

  1. 深入理解各种数据结构的特性和适用场景

  2. 掌握C++内存管理和性能优化技巧

  3. 合理利用现代C++特性简化代码并提升效率

  4. 针对具体问题选择或设计最合适的数据结构

开发者可以构建出既高效又可维护的系统级应用程序。持续学习和实践是掌握这一强大组合的关键。

58 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传