Advertisement
RobertDeMilo

RB4.6 Неинвалидация итераторов списка

Apr 18th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <list>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. class NumbersOnVector
  9. {
  10. public:
  11.     void Add(int x)
  12.     {
  13.         data.push_back(x);
  14.     }
  15.  
  16.     template<typename Predicate>
  17.     void Remove(Predicate predicate)
  18.     {
  19.         data.erase(
  20.                 remove_if(begin(data),end(data),predicate),
  21.                 data.end());
  22.     }
  23.  
  24. private:
  25.     vector<int> data;
  26.  
  27. };
  28.  
  29.  
  30. class NumbersOnList
  31. {
  32. public:
  33.     void Add(int x)
  34.     {
  35.         data.push_back(x);
  36.     }
  37.  
  38.     template<typename Predicate>
  39.     auto FindLast(Predicate predicate)
  40.     {
  41.         return find_if(rbegin(data),rend(data),predicate);
  42.     }
  43.  
  44.     template<typename Predicate>
  45.     void Remove(Predicate predicate)
  46.     {
  47.         data.remove_if(predicate);
  48.     }
  49.  
  50. private:
  51.     list<int> data;
  52.  
  53. };
  54.  
  55. const int SIZE = 10000;
  56. const int REMOVAL_COUNT = 1000;
  57.  
  58. int main()
  59. {
  60.     {
  61.         //LOG_DURATION("list");
  62.         NumbersOnList numbers;
  63.  
  64.         for (int i = 0; i < SIZE; ++i)
  65.         {
  66.             numbers.Add(i);
  67.         }
  68.  
  69.         auto it = numbers.FindLast([](int x ){return x%REMOVAL_COUNT==0;});
  70.  
  71.         for(int i=1;i<REMOVAL_COUNT;++i)
  72.         {
  73.             numbers.Remove([i](int x){return x%REMOVAL_COUNT==i;});
  74.         }
  75.         cout<<*it<<" "<<"\n";
  76.  
  77.         while(*it!=0)
  78.         {
  79.             cout<<*it<<" ";
  80.             ++it;
  81.         }
  82.     }
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement