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











