Post

Modern-CPP - Chapter03 - Containers

课程来源:b站我是龙套小果丁

  1. 1
    2
    3
    4
    5
    
    template <typename Range> void Function(Range &range) {
      for (auto &elem : range) {
        elem *= 2;
      }
    }
    
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    #include <iostream>
    #include <iterator>
    #include <ostream>
    #include <vector>
       
    void print_vector(const std::vector<int> &v) {
      std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
      std::cout << std::endl;
    }
       
    int main() {
      std::vector v1(10, 5);
      std::vector v2{2, 1, 4};
       
      v1.insert(v1.begin() + 2, v2.rbegin(), v2.rend());
       
      v1.erase(v1.begin() + 5, v1.end());
       
      v1.erase(
          std::remove_if(v1.begin(), v1.end(), [](int x) { return x % 2 == 1; }),
          v1.end());
      std::vector v3{1, 7};
       
      auto result = v1 <=> v3;
      if (std::is_lt(result))
        std::println("v1 <=> v3: less");
      else if (std::is_gt(result))
        std::println("v1 <=> v3: greater");
      else
        std::println("v1 <=> v3: equal");
    }
    
  3. 1
    2
    3
    4
    5
    
    std::list l1(10, 5);
    std::list l2{2, 1, 4};
    l1.splice(l1.end(), l2, l2.begin(), l2.end());
    l1.unique();
    l1.sort();
    
  4. No, because deque’s typical implementation is using a dynamic circular queue whose elements are pointers. These pointers points to contiguous memory but there’s no single contiguous memory that could be returned by a .data() method that would give access to all elements.

  5. 后插入的情况有可能因为容量不够导致重分配,从而使迭代器失效

  6. 最开始it指向vec中的第一个10。erase函数的内部实现是remove,而remove会把所有不等于it指向的元素前移:

    1
    2
    3
    4
    
    [10, 2, 3 ,10, 4], it -> 10
    [2, 10, 3, 10, 4], it -> 2
    [2, 3, 10, 10, 4], it -> 2
    [2, 3, 10, 4, 10], it -> 2
    

    it所指向的值在过程中发生改变,因此造成错误

This post is licensed under CC BY 4.0 by the author.