fork download
  1. #include<vector>
  2. #include<algorithm>
  3. #include<string>
  4.  
  5. struct StructC {
  6. std::string mCommonField;
  7. int mFloatValue; // cherry picked from StructA
  8. short mValue2; // // cherry picked from StructB
  9. };
  10.  
  11. // common field used for set intersection
  12. struct StructA {
  13. std::string mCommonField;
  14. float mFloatValue;
  15. operator StructC() { return {mCommonField, int(mFloatValue), 0}; }
  16. };
  17.  
  18. struct StructB {
  19. std::string mCommonField;
  20. int mValue1;
  21. short mValue2;
  22. operator StructC() { return {mCommonField, 0, mValue2}; }
  23. };
  24.  
  25. #include <iostream>
  26. #include <iterator>
  27.  
  28. template<typename CharT, typename Traits>
  29. std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, StructA const& sa) {
  30. return os << sa.mCommonField << " - " << sa.mFloatValue << std::endl;
  31. }
  32.  
  33. template<typename CharT, typename Traits>
  34. std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, StructC const& sa) {
  35. return os << sa.mCommonField << " - " << sa.mFloatValue << " - " << sa.mValue2 << std::endl;
  36. }
  37.  
  38. int main() {
  39. struct Common {
  40. std::string const& mCommonField;
  41. Common(StructA const& sa) : mCommonField{sa.mCommonField} {};
  42. Common(StructB const& sb) : mCommonField{sb.mCommonField} {};
  43. };
  44. auto cmp = [](Common const& lhs, Common const& rhs) { return lhs.mCommonField < rhs.mCommonField; };
  45.  
  46. // initially unsorted list
  47. std::vector<StructA> aStructs = {{"hello", 1.0f}, {"goodbye", 2.0f}, {"foo", 3.0f}};
  48. // initially unsorted list
  49. std::vector<StructB> bStructs = {{"hello", 1, 2}, {"goodbye", 3, 4}, {"bar", 5, 6}};
  50. // sorting both sets before calling std::intersection
  51. std::sort(aStructs.begin(), aStructs.end(), cmp);
  52. std::sort(bStructs.begin(), bStructs.end(), cmp);
  53.  
  54. std::vector<StructC> union_intersection;
  55. std::set_intersection(aStructs.begin(), aStructs.end(),
  56. bStructs.begin(), bStructs.end(),
  57. std::back_inserter(union_intersection),
  58. cmp);
  59.  
  60. std::copy(union_intersection.begin(), union_intersection.end(),
  61. std::ostream_iterator<StructC>(std::cout, ""));
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3488KB
stdin
Standard input is empty
stdout
goodbye - 2 - 0
hello - 1 - 0