How do I delete from an array using iterators.

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
// Using iterator to delete code from cin

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    vector<string> utility;
    utility.push_back("Knife");
    utility.push_back("Food");
    utility.push_back("Bag");
    
    vector<string>::const_iterator iter;
    
    
    string choice;
    cout << "Enter to find what is in Bag.\n";
    cout << "'Knife', 'Food', 'Bag'\n";
    cin >> choice;
    
    iter = find(utility.begin(), utility.end(), choice);
    if (iter != utility.end())
    cout << "We found " << choice << endl;
    cout << "We are now erasing " << choice << endl;
    
    utility.erase(utility.begin(iter));
    
    system("pause");
    return 0;
}

I try to delete a choice from an iterator but its not working, its just a test. I was wondering if possible.
Last edited on
Change line 29 to utility.erase(iter);
You might also have to change iter to a normal iterator. It should work with const_iterator but not all compilers support it yet.
begin doesn't take any arguments and doesn't have anything to do on line 29 at all. Also, you're missing {}s after the if. Other than that, it look ok. For reference, see the example on http://cplusplus.com/reference/stl/vector/erase/
slow..
Last edited on
Topic archived. No new replies allowed.