c++之旅:模板库中的容器

容器

C++中的容器包括array, vector, list,map,set

数组

array不可变长,创建时其大小就固定了,array中可以存储各种数据类型包括对象,不过array是在栈上分配的,如果存储的数据量比较大可能导致栈溢出

#include <string>
#include <array>
#include <iostream>

using namespace std;
int main(int argc, char **argv) {
    array<string, 5> arrString = {"1", "2", "3", "4", "5"};
    array<int, 4> arrInt = {1,2,3,4};
    for (string str : arrString)
        cout << str << endl;
    for (int i : arrInt)
        cout << i << endl;
}

vector

vector是在堆上创建的,所以其存储容量是无限的。其底层先通过malloc分配一定的空间,如果空间不够了通过realloc重新分配,所以vector底层本质是数组

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char **argv) {
    vector<int> myVector;
    for (int i = 1; i<11; i++) {
       myVector.push_back(i); //尾部插入元素
    }
    
    //返回尾部元素
    cout << myVector.back() << endl;
    //获取10处的元素
    cout << myVector.at(9) << endl;
    //迭代访问
    for (int i : myVector)
        cout << i << endl;
}

list

list底层使用链表来实现的,其成员函数和vector大部分是一样的

#include <list>
#include <iostream>

using namespace std;

int main(int argc, char **argv) {
    list<int> myList;
    for (int i = 1; i<11; i++) {
       myList.push_back(i);
    }
    
    //返回尾部元素
    cout << myList.back()<< endl;
    //在第8个位置插入100
    //创建迭代器(本质是指针)
    std::list<int>::iterator it = myList.begin();
    for(int i=0; i<8; i++)
        it++;
    myList.insert(it, 100);
    //迭代访问
    for (int i : myList)
        cout << i << endl;
}

map

map的底层通过红黑树来实现

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main () {
    map<string,int> mymap = {
                { "a", 10 },
                { "b", 0 },
                { "c", 0 } };
    //插入元素
    mymap.insert (pair<string,int>("d",100));
    cout << mymap.at("d") << endl;
    //查找元素并删除
    map<string,int>::iterator it = mymap.find("c");
    if (it != mymap.end())
        mymap.erase (it);
    //删除元素
    mymap.erase ("b");  
    
    return 0;
}
原文地址:https://www.cnblogs.com/xidongyu/p/6916473.html