C++常见容器一网打尽
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                在C++中,常见的容器包括:
- std::vector:动态数组
- std::list:双向链表
- std::deque:双端队列
- std::set:有序集合(基于红黑树)
- std::map:有序映射(基于红黑树)
- std::multiset:有序集合(可有重复元素,基于红黑树)
- std::multimap:有序映射(可有重复键,基于红黑树)
- std::unordered_set:哈希集合(无序)
- std::unordered_map:哈希映射(无序)
- std::unordered_multiset:哈希集合(可有重复元素)
- std::unordered_multimap:哈希映射(可有重复键)
- std::stack:栈
- std::queue:队列
- std::priority_queue:优先级队列
- std::bitset:位集
- std::string:字符串
- std::array:固定大小数组
以下是创建和使用这些容器的简单示例代码:
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
 
int main() {
    // Vector
    std::vector<int> vec = {1, 2, 3, 4, 5};
    vec.push_back(6); // 添加元素
 
    // List
    std::list<int> lst = {1, 2, 3, 4, 5};
    lst.push_back(6); // 添加元素
 
    // Deque
    std::deque<int> dq = {1, 2, 3, 4, 5};
    dq.push_back(6); // 添加元素
 
    // Set
    std::set<int> st = {1, 2, 3, 4, 5};
    st.insert(6); // 添加元素
 
    // Map
    std::map<int, std::string> mp;
    mp[1] = "one";
    mp[2] = "two";
 
    // Unordered Set
    std::unordered_set<int> uset = {1, 2, 3, 4, 5};
    uset.insert(6); // 添加元素
 
    // Unordered Map
    std::unordered_map<int, std::string> umap;
    umap[1] = "one";
    umap[2] = "two";
 
    // Stack
    std::stack<int> stk;
    stk.push(1); // 添加元素
 
    // Queue
    std::queue<int> q;
    q.push(1); // 添加元素
 
    // Priority Queue (max heap by default)
    std::priority_queue<int> pq;
    pq.push(1); // 添加元素
 
    return 0;
}这些示例展示了如何创建和使用每种容器的基本功能。每个容器都有自己的优点和局限性,选择合适的容器取决于具体的应用场景。
评论已关闭