How To: Transfer elements between vectors in C++

Sometimes I end up needing to do this, so I re-implement the functionality… And it segfaults or behaves strangely. This time I’ll write it down somewhere I know where I can find it!

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. 	// Create an empty vector of type string for our shopping list
  10. 	vector<string> shoppingList;
  11.  
  12. 	// Add a few items to it
  13. 	shoppingList.push_back("Milk");
  14. 	shoppingList.push_back("Bread");
  15. 	shoppingList.push_back("Eggs");
  16.  
  17. 	// Create an empty vector of type string for our purchases
  18. 	vector<string> purchases;
  19.  
  20. 	// Create a string to hold the user's answer
  21. 	string answer;
  22.  
  23. 	// Transfer items bought from the shopping list to the purchases list (includes removal from the shoppingList vector)
  24. 	vector<string>::iterator i = shoppingList.begin();
  25. 	while (i != shoppingList.end() )
  26. 	{
  27. 		cout << "Item: " << *i << endl;
  28. 		cout << "Purchase item? (y/n)" << endl;
  29.  
  30. 		cin >> answer;
  31.  
  32. 		// If we said yes...
  33. 		if (answer == "y")
  34. 		{
  35. 			// ...add the item to the purchases vector and...
  36. 			purchases.push_back(*i);
  37.  
  38. 			// ...remove the item from the shoppingList vector. Erase returns an
  39. 			// iterator which points at the next element in the vector, so we need to
  40. 			// skip incrementing the iterator in this case or we might go out of bounds!
  41. 			i = shoppingList.erase(i);
  42. 		}
  43. 		else // Otherwise just move on to the next item!
  44. 		{
  45. 			i++;
  46. 		}
  47. 	}
  48.  
  49. 	cout << endl;
  50.  
  51. 	// Display both lists
  52. 	cout << "----- Shopping List ----" << endl;
  53. 	for (i = shoppingList.begin(); i != shoppingList.end(); i++)
  54. 	{
  55. 		cout << *i << endl;
  56. 	}
  57.  
  58. 	cout << endl;
  59.  
  60. 	cout << "----- Purchases ----" << endl;
  61. 	for (i = purchases.begin(); i != purchases.end(); i++)
  62. 	{
  63. 		cout << *i << endl;
  64. 	}
  65.  
  66. 	cout << endl;
  67.  
  68. 	return 0;
  69. }

TLTB ;-)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.