fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. struct Object {
  6. size_t id;
  7. size_t state;
  8. };
  9.  
  10. struct LessByAllFields {
  11. bool operator()(const Object &first, const Object &second) {
  12. if (first.id == second.id) {
  13. return first.state < second.state;
  14. }
  15. return first.id < second.id;
  16. }
  17. };
  18.  
  19. struct LessById {
  20. bool operator()(const Object &first, const Object &second) {
  21. return first.id < second.id;
  22. }
  23. };
  24.  
  25. std::ostream &operator<<(std::ostream &out, const Object &obj) {
  26. return out << "id " << obj.id << " state " << obj.state << ' ';
  27. }
  28.  
  29. std::ostream &operator<<(std::ostream &out,
  30. const std::vector<Object> &objects) {
  31. for (auto object : objects) {
  32. out << object << ' ';
  33. }
  34. return out << '\n';
  35. }
  36.  
  37. template <typename Comp>
  38. std::vector<Object> UniqueInFirst(const std::vector<Object> &first,
  39. const std::vector<Object> &second,
  40. Comp comp) {
  41. std::vector<Object> unique_in_first;
  42. std::set_difference(second.begin(), second.end(), first.begin(), first.end(),
  43. std::back_inserter(unique_in_first), comp);
  44. return unique_in_first;
  45. }
  46.  
  47. template <typename Comp>
  48. std::vector<Object> Intersection(const std::vector<Object> &first,
  49. const std::vector<Object> &second, Comp comp) {
  50. std::vector<Object> unique_in_first;
  51. std::set_intersection(first.begin(), first.end(), second.begin(),
  52. second.end(), std::back_inserter(unique_in_first),
  53. comp);
  54. return unique_in_first;
  55. }
  56.  
  57. int main() {
  58. std::vector<Object> old = {{0, 0}, {1, 1}, {2, 2}, {3, 3}};
  59. std::vector<Object> current = {{4, 4}, {0, 0}, {2, 3}, {3, 5}};
  60.  
  61. std::sort(old.begin(), old.end(), LessByAllFields());
  62. std::sort(current.begin(), current.end(), LessByAllFields());
  63.  
  64. std::cout << "Old vector : " << old;
  65. std::cout << "Current vector : " << current;
  66. std::cout << "Only new elements : " << UniqueInFirst(old, current,
  67. LessByAllFields());
  68. std::cout << "Only old elements : " << UniqueInFirst(current, old,
  69. LessByAllFields());
  70. std::cout << "Same with state changed: \n"
  71. << "in old: " << Intersection(old, current, LessById())
  72. << "in new: " << Intersection(current, old, LessById());
  73. }
  74.  
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
Old vector             : id 0 state 0  id 1 state 1  id 2 state 2  id 3 state 3  
Current vector         : id 0 state 0  id 2 state 3  id 3 state 5  id 4 state 4  
Only new elements      : id 2 state 3  id 3 state 5  id 4 state 4  
Only old elements      : id 1 state 1  id 2 state 2  id 3 state 3  
Same with state changed: 
in old: id 0 state 0  id 2 state 2  id 3 state 3  
in new: id 0 state 0  id 2 state 3  id 3 state 5