Iterator throwing an error when converting to string*

Consider the following piece of code:

bool SearchElement(const string& product) {
 
   for (list<string>::iterator it = elements.begin(); it != elements.end();i++)    {
      string& element = *it;
    if ( element == product){return true;}

   } return false; 
}

I want to rewrite it using a pointer:

 bool SearchElement(const string& product) {
    
       for (list<string>::iterator it = elements.begin(); it != elements.end();i++)    {
          string* pelement = it;
        if ( *pelement == product){return true;}
    
       } return false;    }

But it is throwing an error:

C:\Users...\C++\IShoppingApp.h:141: error: cannot convert 'std::__cxx11::liststd::__cxx11::basic_string<char >::iterator' {aka 'std::_List_iteratorstd::__cxx11::basic_string<char >'} to 'std::__cxx11::string*' {aka 'std::__cxx11::basic_string*'} in initialization In file included from C:/Users/....

My professor said an iterator is roughly speaking a pointer, so I expected to use it as such. Why am I getting this error and how do I fix it?



Read more here: https://stackoverflow.com/questions/66483950/iterator-throwing-an-error-when-converting-to-string

Content Attribution

This content was originally published by J.C.VegaO at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: