首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ 進階容器與算法實戰:multimap、multiset、bitset、string 及 Lambda 表達式全解析

     編輯:關於C++

關聯容器:multiset 與 multimap

multiset — 允許重複元素的有序集合

#include 
#include 
using namespace std;

void demo_multiset() {
    multiset ms;
    ms.insert(100); ms.insert(101); ms.insert(100); ms.insert(103); ms.insert(100);
    
    // 查找單個元素(返回任意一個 101 的迭代器)
    auto it = ms.find(101);
    cout << "find(101): " << *it << endl;
    
    // equal_range 返回所有等於 100 的元素範圍 [first, second)
    auto range = ms.equal_range(100);
    cout << "所有 100: ";
    for (auto i = range.first; i != range.second; ++i)
        cout << *i << ' ';
    cout << endl;
}

關鍵點:底層紅黑樹,插入/刪除/查找 O(log n);equal_range 批量訪問同值元素極高效。

multimap — 允許重複鍵的映射

#include 
#include 
#include 
using namespace std;

void demo_multimap() {
    multimap mm;
    mm.insert({"yincheng", "a"});
    mm.insert({"yincheng1", "b"});
    mm.insert({"yincheng", "c"});
    mm.insert({"yincheng", "d"});
    
    // 遍歷所有
    for (auto& kv : mm) cout << kv.first << " " << kv.second << endl;
    
    // 查找鍵 "yincheng" 的所有值
    auto range = mm.equal_range("yincheng");
    for (auto it = range.first; it != range.second; ++it)
        cout << it->first << " " << it->second << endl;
}

bitset — 定長位向量,高效位運算

#include 
#include 
using namespace std;

void demo_bitset() {
    // 1. 構造:從整數
    bitset<8> bs(215); // 11010111
    cout << "正序(低位在前): ";
    for (int i = 0; i < 8; ++i) cout << bs[i]; // 輸出 11101011 (反序)
    cout << "\n逆序(高位在前): ";
    for (int i = 7; i >= 0; --i) cout << bs[i] << ' ' << ~bs[i] << endl;
    
    // 2. 浮點數/負數的位模式查看
    bitset<32> fbits(1231231236.8f); // 隱式轉換為 unsigned long
    bitset<32> nbits(-5);            // 補碼表示
    
    // 3. 常用操作
    bitset<8> b(255);
    b.set(7, 0); b.set(0, 0); // 置位/清位
    cout << "size: " << b.size() << ", to_ulong: " << b.to_ulong() << endl;
    // b.reset(); b.any(); b.none(); b.count();
}

注意:bitset[N] 下標 0 為最低位(LSB),輸出時常需逆序遍歷;to_ulong() 可能拋出 overflow。

string 容器核心操作速查

操作代碼示例說明
構造/賦值string s("abc"); s = "def";支援 C 風格字符串、字符重複、子串構造
拼接s1 + s2; s1 += s2; s1.append(s2);+= 可原地擴展,避免臨時對象
插入s.insert(pos, n, 'x'); s.insert(it, 'x');pos 可為下標或迭代器
刪除s.erase(pos, len); s.erase(it); s.erase(first, last);靈活支持下標/迭代器區間
替換s.replace(pos, len, "new");替換指定區間
查找s.find("sub"); s.rfind("sub"); s.find_first_of("set");返回 size_t,未找到返回 npos
比較s1 == s2; s1.compare(s2);重載運算符按字典序比較
C 兼容s.c_str(); s.data();返回 const char*,注意生命週期

算法、仿函數與 Lambda 表達式

仿函數

template 
struct Doubler {
    void operator()(T& x) { x *= 2; cout << x << '\n'; }
};

vector v = {10, 9, 7, 9};
for_each(v.begin(), v.end(), Doubler()); // 臨時對象調用

Lambda 表達式 (C++11)

auto add = [](int a, int b) { return a + b; };
cout << add(1, 2) << endl; // 3

// 修改容器元素
for_each(v.begin(), v.end(), [](int& x) { x *= 2; cout << x << endl; });

// 捕獲外部變量
int factor = 10;
auto mul = [factor](int x) { return x * factor; }; // 值捕獲
auto mul_ref = [&factor](int x) { return x * factor; }; // 引用捕獲

GPU 並行計算入門

AMP (Accelerated Massive Parallelism) 允許 C++ 直接在 GPU 上執行數據並行計算:

#include 
#include 
using namespace concurrency;
using namespace std;

void gpu_hello() {
    int a[10] = {1,2,3,4,5,6,7,8,9,10};
    array_view av(10, a); // 自動同步到 GPU
    
    parallel_for_each(av.extent, [=](index<1> idx) restrict(amp) {
        av[idx] += 123; // GPU 並行執行
    });
    
    for (int i = 0; i < 10; ++i) cout << av[i] << endl; // 同步回 CPU
}

性能對比:CPU vs GPU

// 單點計算:CPU 勝出(時鐘頻率高、延遲低)
// 大規模並行:GPU 勝出(成百上千核心並發)
// 關鍵 API:
// parallel_for_each(extent, lambda restrict(amp))
// array_view::synchronize() // 顯式同步
// restrict(amp) / restrict(cpu) / restrict(amp, cpu)

GPU 調試設置 CPU/GPU 適用場景

總結

  • multiset/multimap:處理重複鍵值場景首選,equal_range 是批量訪問利器
  • bitset:定長位運算極致效率,適合標誌位集合、位掩碼、二進制數值分析
  • string:掌握插入/刪除/替換/查找各重載,善用 += 避免拷貝
  • Lambda + STL 算法:現代 C++ 風格,內聯展開零開銷,替代繁瑣仿函數
  • AMP/GPU:數據並行密集型計算(圖像處理、科學計算、深度學習預處理)可獲數量級加速
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved