C++中,标准库数据结构

在C++中,也有一套丰富的标准库数据结构(主要在 <vector>, <map>, <set>, <unordered_map>, <unordered_set> 等头文件中),它们可以和Python中的 list, dict, set 对应起来。下面是一个对比总结,帮你快速建立映射关系:


🟢 Python list ⇨ C++ 对应数据结构

PythonC++ 等效特性
liststd::vector动态数组,支持随机访问,插入删除效率较低(除非在尾部)
std::list双向链表,插入删除效率高,但不支持随机访问
std::deque双端队列,两端插入删除都快,支持随机访问

✅ 通常用 std::vector 替代 Python 的 list,除非你特别需要链表性质或双端操作。


🟡 Python dict ⇨ C++ 对应数据结构

PythonC++ 等效特性
dictstd::map基于红黑树,键有序,查找/插入/删除是 O(log n)
std::unordered_map基于哈希表,键无序,查找/插入/删除是 O(1)(均摊)

✅ 如果你不在乎顺序,用 unordered_map 更快;需要有序键值对,用 map


🔵 Python set ⇨ C++ 对应数据结构

PythonC++ 等效特性
setstd::set红黑树实现,元素有序,去重
std::unordered_set哈希表实现,元素无序,去重,操作更快

✅ Python 的 set 更像 unordered_set,不过 C++ 提供有序和无序两种版本。


✅ 补充

C++ 结构类似Python用途
std::stack, std::queuecollections.deque, 手动控制 list先进后出 / 先进先出
std::priority_queueheapq最小堆 / 最大堆
std::pair, std::tupletuple打包数据
std::array (C++11+)tuple, list固定大小数组

Comments

  1. Owner
    1 month ago
    2025-4-24 3:49:25

    举几个常见的数据结构操作的 Python 和 C++ 对照例子。这样你一眼就能看出来它们之间怎么映射、怎么用法类似。

    🟢 1. listvector

    ✅ Python

    lst = [1, 2, 3]
    lst.append(4)
    lst[1] = 10
    print(lst[2])

    ✅ C++

    #include <vector>
    #include <iostream>
    using namespace std;
    
    int main() {
        vector<int> lst = {1, 2, 3};
        lst.push_back(4);
        lst[1] = 10;
        cout << lst[2] << endl;
    }

    🟡 2. dictunordered_map

    ✅ Python

    d = {'a': 1, 'b': 2}
    d['c'] = 3
    print(d['b'])

    ✅ C++

    #include <unordered_map>
    #include <iostream>
    using namespace std;
    
    int main() {
        unordered_map<string, int> d;
        d["a"] = 1;
        d["b"] = 2;
        d["c"] = 3;
        cout << d["b"] << endl;
    }

    (如果你要用有序的键,用 map

    🔵 3. setunordered_set

    ✅ Python

    s = {1, 2, 3}
    s.add(4)
    print(2 in s)

    ✅ C++

    #include <unordered_set>
    #include <iostream>
    using namespace std;
    
    int main() {
        unordered_set<int> s = {1, 2, 3};
        s.insert(4);
        cout << (s.count(2) > 0) << endl;  // 输出 1 表示存在
    }

    🔁 4. 遍历

    ✅ Python for 遍历

    for x in [1, 2, 3]:
        print(x)

    ✅ C++ 范围for循环(C++11 起)

    for (int x : vector<int>{1, 2, 3}) {
        cout << x << endl;
    }
  2. Owner
    1 month ago
    2025-4-24 3:50:58

    排序、查找和过滤是常见的操作,C++ 和 Python 中的用法其实有一些相似,但也有各自的特点。我们一起看下这几个操作的对比:

    🟢 1. 排序 (Sorting)

    ✅ Python

    Python 的 list.sort()sorted() 用于排序,默认是升序的,可以用 reverse=True 降序排序,或者用 key 参数指定自定义排序。

    lst = [3, 1, 4, 1, 5, 9, 2, 6]
    lst.sort()  # 原地排序
    print(lst)
    
    # 或者使用 sorted 返回新的排序列表
    sorted_lst = sorted(lst, reverse=True)
    print(sorted_lst)

    ✅ C++

    C++ 使用 std::sort 来排序,std::sort 默认升序排列。如果需要降序或自定义排序,可以传入比较函数。

    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    int main() {
        vector<int> lst = {3, 1, 4, 1, 5, 9, 2, 6};
    
        // 升序排序
        sort(lst.begin(), lst.end());
        for (int x : lst) cout << x << " ";
        cout << endl;
    
        // 降序排序
        sort(lst.begin(), lst.end(), greater<int>());
        for (int x : lst) cout << x << " ";
        cout << endl;
    }

    🟡 2. 查找 (Search)

    ✅ Python

    Python 提供了 in 操作符来检查元素是否在集合(如 list, set, dict)中,index() 方法可以查找元素的索引。

    lst = [1, 2, 3, 4, 5]
    print(3 in lst)  # 返回 True
    print(lst.index(4))  # 返回 3 (索引)

    ✅ C++

    C++ 有 std::find 来查找元素,也可以使用 count() 来检查元素是否存在。

    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    int main() {
        vector<int> lst = {1, 2, 3, 4, 5};
    
        // 查找元素是否在容器中
        if (find(lst.begin(), lst.end(), 3) != lst.end()) {
            cout << "Found 3!" << endl;
        } else {
            cout << "Not found!" << endl;
        }
    
        // count 检查元素个数(可以用来检查是否存在)
        cout << count(lst.begin(), lst.end(), 4) << endl;  // 输出 1
    }

    🔵 3. 过滤 (Filter)

    ✅ Python

    Python 使用 filter() 或者列表推导式来进行过滤操作。

    lst = [1, 2, 3, 4, 5, 6]
    even_lst = list(filter(lambda x: x % 2 == 0, lst))  # 使用 filter 函数
    print(even_lst)
    
    # 或者使用列表推导式
    even_lst = [x for x in lst if x % 2 == 0]
    print(even_lst)

    ✅ C++

    C++ 使用 std::copy_if 来过滤元素(结合标准库算法),需要用到额外的容器来存储过滤结果。

    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    int main() {
        vector<int> lst = {1, 2, 3, 4, 5, 6};
        vector<int> even_lst;
    
        // 过滤偶数
        copy_if(lst.begin(), lst.end(), back_inserter(even_lst), [](int x) { return x % 2 == 0; });
    
        for (int x : even_lst) cout << x << " ";
        cout << endl;
    }

    🟣 小结

    1. 排序:Python 和 C++ 都有排序功能,Python 的 sort() 更直观,C++ 通过 std::sort 提供了更高的灵活性和性能优化。
    2. 查找:Python 直接用 inindex(),C++ 使用 std::findcount 来进行查找,功能上差不多,但 C++ 需要写得更详细些。
    3. 过滤:Python 用 filter() 或列表推导式,C++ 使用 std::copy_if 结合 lambda 表达式来过滤,C++ 稍显复杂但更灵活。

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
Previous
Next