• 每日学习笔记:C++ STL 的forward_list


    定义

    特点

     

    操作函数

     

     

    元素查找、移除或安插

    forward_list::emplace_after

    arg...指的是元素构造函数的参数(0~N个)

    1. #include
    2. #include
    3. #include
    4. #include
    5. using namespace std;
    6. class aaa
    7. {
    8. public:
    9. aaa() {
    10. c = 666;
    11. };
    12. aaa(int a, int b) {
    13. c = a + b;
    14. };
    15. friend std::ostream& operator << (std::ostream& o, const aaa& s) {
    16. o << s.c;
    17. return o;
    18. }
    19. private:
    20. int c;
    21. };
    22. int main()
    23. {
    24. forward_list t1{ {1,1},{},{2,2} };
    25. std::copy(t1.cbegin(), t1.cend(), std::ostream_iterator(cout, " "));
    26. cout << endl;
    27. t1.emplace_after(t1.before_begin(), 6, 8);
    28. std::copy(t1.cbegin(), t1.cend(), std::ostream_iterator(cout, " "));
    29. cout << endl;
    30. t1.emplace_after(t1.before_begin());
    31. std::copy(t1.cbegin(), t1.cend(), std::ostream_iterator(cout, " "));
    32. cout << endl;
    33. forward_list<int> t{ 1,2,3 };
    34. t.emplace_after(t.before_begin(), 55);
    35. std::copy(t.cbegin(), t.cend(), std::ostream_iterator<int>(cout, "-"));
    36. for (;;);
    37. }

    forward_list::splice_after

    标准库第二版>书中介绍了c.splice_after(pos,c2,c2pos)的定义【c2pos所指的下一个转移到pos所指的下一个】,但是示例代码却写成了

    这个调用的参数顺序与函数定义的参数顺序并不一致,于是我专门验证了一下,发现这个写法的运行结果与按照函数定义的参数顺序t2.splice_after(pos2, t1, pos1);运行结果居然相同,甚至我改成了下面这样的调用,结果仍然相同

    1. forward_list<int> t3; //定义一个空的forward_list
    2. t3.splice_after(pos2, forward_list<int>(), pos1); //形参传入一个空的forward_list

    细看了一下 splice_after函数实现发现,在没有开启DEBUG宏的情况下,其内部并没有操作形参传入的forward_list参数,而只是对迭代器pos2、pos1之右(后)所指内容进行了拼接。即常规的单向链表拼接的指针操作。

    示例代码:

    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. forward_list<int> t1{1,2,3,4,5};
    7. forward_list<int> t2{ 97,98,99};
    8. auto pos1 = t1.before_begin();
    9. for (auto pb1 = t1.begin(); pb1 != t1.end(); ++pb1,++pos1)
    10. {
    11. if (*pb1 == 3)
    12. {
    13. break;
    14. }
    15. }
    16. auto pos2 = t2.before_begin();
    17. for (auto pb2 = t2.begin(); pb2 != t2.end(); ++pb2, ++pos2)
    18. {
    19. if (*pb2 == 99)
    20. {
    21. break;
    22. }
    23. }
    24. t1.splice_after(pos2, t2, pos1);
    25. //t2.splice_after(pos2, t1, pos1);
    26. //forward_list t3;
    27. //t3.splice_after(pos2, forward_list(), pos1);
    28. //t2.splice_after(pos2, t1, t1.before_begin());
    29. //t2.splice_after(pos2, t1, t1.begin());
    30. for (;;);
    31. }

  • 相关阅读:
    安装gpu版本的paddle
    uni-app基于vue实现商城小程序
    Vue2项目引入element ui的表格第一行有输入框要禁用
    小程序隐私弹窗的实现
    ElasticSearch - 初步检索
    单例模式之「双重校验锁」
    明明加了唯一索引,为什么还是产生重复数据?
    Hbuilder打包安卓H5-APP,APP与程序分离,更新无需重新打包
    项目实战 | 责任链模式 (下)
    算法 数据结构 递归冒泡算法 java冒泡算法 优化递归冒泡 数据结构(九)
  • 原文地址:https://blog.csdn.net/Jane_Yih/article/details/136672918