c++ - Vector Erase Error -


i have following code in c++:

#include <iostream> #include <cstdlib> #include <ctime> #include <vector> int main () {     srand(time(0));     int noofelements = 9;     (int = 0; < 9; a++)     {         std::vector<int> poss;         (int = 1; <= 9; a++)             poss.push_back(a);         (int b = 0; b < 9; b++)         {             int random = rand() % 9;             std::cout << poss[random];             poss.erase(random);             noofelements--;         }         std::cout << "\n";     } } 

yet when run it, returns this:

error: no matching function call 'std::vector<int>::erase(int&)' 

for line 13.

why , how can correct it?

you cannot erase values vector directly (vectors sequence containers, not associative containers): need provide iterator element want erased.

in order iterator, may either:

  • find element based on value (e.g. using std::find()) , provide returned iterator in input erase() member function, or
  • get applying offset iterator points beginning of vector (i.e. object returned begin() member function).

in first case:

#include <vector> #include <algorithm>  int main() {     std::vector<int> v { 1, 2, 3};     auto = std::find(begin(v), end(v), 2);     v.erase(i); } 

the above code uses c++11 features. in c++03, follows:

#include <vector> #include <algorithm>  int main() {     std::vector<int> v;      v.push_back(1);     v.push_back(2);     v.push_back(3);      std::vector<int>::iterator = std::find(v.begin(), v.end(), 2);     v.erase(i); } 

in second case, if know index of element inside vector (say, pos), can iterator way:

v.begin() + pos 

alternatively (c++11 only) do:

next(begin(v), pos); 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -