fork download
  1. using namespace std;
  2. #include <iostream>
  3. #include <vector>
  4.  
  5.  
  6. // combine two sorted lists A and B into R
  7. // displays comparison every time it is done
  8. void combine(const vector<int>& A, const vector<int>& B, vector<int>& R)
  9. {
  10. auto itA = A.begin();
  11. auto itB = B.begin();
  12.  
  13. while ( (itA != A.end()) && (itB != B.end()) )
  14. {
  15. if (*itA < *itB)
  16. {
  17. R.push_back(*itA);
  18. itA++;
  19. }
  20. else
  21. {
  22. R.push_back(*itB);
  23. itB++;
  24. }
  25. }
  26. while(itA != A.end())
  27. {
  28. R.push_back(*itA);
  29. itA++;
  30. }
  31. while(itB != B.end())
  32. {
  33. R.push_back(*itB);
  34. itB++;
  35. }
  36. cout << "comparison" << endl;
  37. // be careful -- R comes in as an empty vector
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. vector<int> L1;
  44. vector<int> L2;
  45. vector<int> L3;
  46. int N; // how many elements in each of L1 and L2
  47. int e; // for each element
  48.  
  49. cout << "How many elements in each list?" << endl;
  50. cin >> N;
  51.  
  52. cout << "List1" << endl;
  53. for (int i = 0; i < N; i++)
  54. {
  55. cout << "element :"<<endl; cin >> e; L1.push_back(e);
  56. }
  57.  
  58. cout << endl << "List2" << endl;
  59. for (int i = 0; i < N; i++)
  60. {
  61. cout << "element :"<<endl; cin >> e; L2.push_back(e);
  62. }
  63.  
  64. combine(L1, L2, L3);
  65.  
  66.  
  67. cout << "The result is: ";
  68. for (int i = 0; i < N * 2; i++)
  69. {
  70. cout << L3[i]<<" | ";
  71. } cout << endl;
  72.  
  73. }// end of main
Success #stdin #stdout 0s 4404KB
stdin
3
1 3 5 2 4 6
stdout
How many elements in each list?
List1
element :
element :
element :

List2
element :
element :
element :
comparison
The result is: 1 | 2 | 3 | 4 | 5 | 6 |