4. OOP: STL(vector, list, map)

STL(vector, list, map)

0. Overview:

STL is the soul of C++. Remember this, mastering the STL is master the most part of C++. Though array is more efficient than vector, vector is still the feature of C++. In this sector, we will discuss the basic usage of vector, list, and map. Simply explain these three STL. Vector is array with intelligent memory allocation/deallocation, which saves us from the size of container; List can be regarded as doubly linked list, specific feature will be covered in the code; Map is hash table, which will be frequently used in algorithm problem.

1. Vector:

Vector is advanced type of array, because vector has more flexible way to
handle problem.

It has member function: size(), front(), end(), push_back(T t), pop_back().

Also, besides the traditional way to iterate the container, you could user iterator in STL to do this.

// vector<int>: vector of int
    // vector<vector<int>>: vector of (vector of int)
    // vector<int *>: the vector of pointers to int
    // vector<vector<int> *>: vector of pointers to vector of int


    // vector
    vector<int> V1 {
   3, 4, 5, 6, 7};
    // 5 5 3 7
    cout << V1.size() << " " << V1[2] << " " << V1.front() << " " << V1.back() << endl;

    // 10 elements; all with initial value 3
    vector<int> V2(10, 3);
    // 6 elements; all with initial value 0
    vector<int> V3(6);

    // add new element 8 to the back of the vector
    V1.push_back(8);

    //remove the last element of the vector
    V1.pop_back();
    
    // print the vector

    // call by value
    // 3 4 5 6 7 8
    for(int i : V1){
    cout << i << " "; i++; }
    cout << endl;
    // The same as above
    // 3 4 5 6 7 8
    for(int i : V1){
    cout << i << " "; }
    cout << endl;

    // call by reference
    // 3 4 5 6 7 8 
    for(int &i : V1){
    cout << i << " "; i++; }
    cout << endl;
    // 4 5 6 7 8 9
    for(int i : V1){
    cout << i << " "; }
    cout << endl;

    // Iterator
    // begin() returns the address of the first element
    // endI() returns the address AFTER the last element
    vector<int>::iterator it1 = V1.begin(), it2 = V1.end();
    auto it3 = V1.begin();

    for(auto it6 = V1.begin(); it6 != V1.end(); it6++){
   
        cout << *it6 << " ";
    }
    
    auto it10 = V1.begin() + 10;
    // auto can be very handful
    // map<int , vector<list<int*> *>:: iterator it5 = M1.begin();
    // auto it5 = M
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值