fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <tuple>
  4. #include <vector>
  5.  
  6. template<typename Pair>
  7. class pair_generator {
  8. public:
  9. explicit pair_generator(std::vector<Pair>& cont)
  10. : cont_(cont)
  11. { }
  12.  
  13. template<typename T>
  14. bool operator()(T l, T r) {
  15. cont_.emplace_back(r, l);
  16. return true;
  17. }
  18. private:
  19. std::vector<Pair>& cont_;
  20. };
  21.  
  22. template<typename Pair>
  23. struct position_independant_compare {
  24.  
  25. explicit position_independant_compare(const Pair& pair)
  26. : pair_(pair)
  27. { }
  28.  
  29. bool operator()(const Pair & p) const {
  30. return (p.first == pair_.first && p.second == pair_.second) || (p.first == pair_.second && p.second == pair_.first);
  31. }
  32. private:
  33. const Pair& pair_;
  34. };
  35.  
  36. template<typename T>
  37. using pair_of = std::pair<T, T>;
  38.  
  39. template<typename T>
  40. std::ostream & operator <<(std::ostream & stream, const pair_of<T>& pair) {
  41. return stream << '[' << pair.first << ", " << pair.second << ']';
  42. }
  43.  
  44. int main() {
  45. std::vector<int>
  46. v1 {0 ,1, 2, 3, 4, 5},
  47. v2 {4, 8, 6, 2, 1, 5, 0, 3};
  48.  
  49. std::vector<pair_of<int> >
  50. p1 { },
  51. p2 { };
  52.  
  53. // generate our pairs
  54. std::sort(v1.begin(), v1.end(), pair_generator<pair_of<int>>{ p1 });
  55. std::sort(v2.begin(), v2.end(), pair_generator<pair_of<int>>{ p2 });
  56.  
  57. // account for the fact that the first and last element are a pair too
  58. p1.emplace_back(p1.front().first, p1.back().second);
  59. p2.emplace_back(p2.front().first, p2.back().second);
  60.  
  61. std::cout << "pairs for vector 1" << std::endl;
  62. for(const auto & p : p1) { std::cout << p << std::endl; }
  63.  
  64. std::cout << std::endl << "pairs for vector 2" << std::endl;
  65. for(const auto & p : p2) { std::cout << p << std::endl; }
  66.  
  67. std::cout << std::endl << "pairs shared between vector 1 and vector 2" << std::endl;
  68. for(const auto & p : p1) {
  69. const auto pos = std::find_if(p2.begin(), p2.end(), position_independant_compare<pair_of<int>>{ p });
  70. if(pos != p2.end()) {
  71. std::cout << p << std::endl;
  72. }
  73. }
  74. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
pairs for vector 1
[0, 1]
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[0, 5]

pairs for vector 2
[4, 8]
[8, 6]
[6, 2]
[2, 1]
[1, 5]
[5, 0]
[0, 3]
[4, 3]

pairs shared between vector 1 and vector 2
[1, 2]
[3, 4]
[0, 5]