I want to use an iterator as a condition of a for loop, but when I define it, it->empty() always reports an error. I don’t know where the error is. When I change it to (*it).empty() It will also report an error later
The error is: the expression must contain a pointer type to the class, but it has type "char *"
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
string s("some string");
for (auto it = s.begin(); it != s.end() && !it->empty(); it )
{
cout<< *it <<endl;
}
}
CodePudding user response:
The problem is that you are trying to access a member function called empty
through a non-class type object(a char
type object in this case). You can change your code to look like below:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
std::vector<std::string> vec = {"some", "string", "is", "this"};
for (auto it = vec.begin(); it != vec.end() && !it->empty(); it )
{
cout<< *it <<endl;
}
}
The above code works because this time we are using/calling the member function empty
through a class type object(a std::string
object in this modified example).
Also if you only wanted to know why you're having this error then i think the comments and my answer, answer that. If you have any other/further question then you can edit your question to add that.