fork(3) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Node
  7. {
  8. int* val;
  9. };
  10.  
  11. // Util method which prints vector
  12. void printVector(vector<Node>& v)
  13. {
  14. vector<Node>::iterator it;
  15.  
  16. for(it = v.begin(); it != v.end(); ++it)
  17. {
  18. cout << *((*it).val) << ", ";
  19. }
  20.  
  21. cout << endl;
  22. }
  23.  
  24. int main() {
  25. vector<Node> v;
  26.  
  27. // Creating a dummy vector
  28. v.push_back(Node()); v[0].val = new int(0);
  29. v.push_back(Node()); v[1].val = new int(10);
  30. v.push_back(Node()); v[2].val = new int(20);
  31. v.push_back(Node()); v[3].val = new int(30);
  32. v.push_back(Node()); v[4].val = new int(40);
  33. v.push_back(Node()); v[5].val = new int(50);
  34. v.push_back(Node()); v[6].val = new int(60);
  35.  
  36. cout << "Vector before insertion - ";
  37. printVector(v); // Prints - 0, 10, 20, 30, 40, 50, 60,
  38.  
  39. // Insert the element of given index to the beginning
  40. v.insert(v.begin(), std::move(v[4]));
  41.  
  42. cout << "Vector after insertion - ";
  43. printVector(v); // Prints - 30, 0, 10, 20, 30, 40, 50, 60,
  44. // Why did 30 get inserted at the beggning and not 40?
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Vector before insertion - 0, 10, 20, 30, 40, 50, 60, 
Vector after insertion - 30, 0, 10, 20, 30, 40, 50, 60,