c++ - vector .erase error c2664 -
i trying iterate through vector , erase specific items it. i'm working form end of vector down don't mess iterator items removed, when try compile it's throwing error. looked through of other posts same error didn't see applied situation, or if there didn't catch it, i'm still pretty new c++ , programming in general. below sample of simpler code illustrate problem.
#include <iostream> #include <vector> using namespace std; int vectorerase(vector<int>, int &); int main() { vector<int> test; for(int i=0; i<11;i++) { test.push_back(i); cout<<test[i]; } for(int i=10;i<=0;i--) { vectorerase(test, i); cout<<test[i]; } system("pause"); return 0; } int vectorerase(vector<int> test, int &iterat) { if(test[iterat]>6) { test.erase(iterat); } return 0; }
any great
the immediate problems in code are:
- passing vector value, original never modified.
- not using
erase()
properly. returns iterator next element in sequence, did not erase (yet). means if use iterators , remove element, need not (and should not) increment iterator. example forth-coming. - in conjunction above, simply, you're not using iterators, , should be.
your code without function , this:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> test; for(int i=0; i<11;i++) { cout << << ' '; test.push_back(i); } cout << '\n'; for(auto = test.begin(); != test.end();) { if (*it > 6) = test.erase(it); else { cout << *it << ' '; ++it; } } cout << '\n'; return 0; }
output
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6
i advise spend few days working iterators. start simple (like example).
Comments
Post a Comment