I have method which chec is client objects exists (by its name) and returns its position:
int Program::checkClient(string userName){
vector<Client> *ptr = &(impl->clients);
int i;
for (i = 0; i < ptr->size(); i++){
if(ptr->at(i).getName() == userName){
return i;
}
}
return -1;
}
The problem is that I get warning, because of i < ptr->size()
. I believe I need to use iterator for this. But how to do it correctly, because not only do I need to run through loop, but also return int as a result, of where it was found. Any ideas? i tried doing something like this, but had no luck:
int Program::checkClient(string userName){
vector<Client> *ptr = &(impl->clients);
vector<Client>::iterator it;
for (it.ptr->begin(); it < it.ptr->end(); it++){
if(ptr->at(it).getName() == userName){
return it;
}
}
return -1;
}
I get an error to similar places like this: it.ptr->begin()
.
You don't need to use iterators; you haven't mentioned what warning you're getting, but it's probably because you're comparing an int
to vector<Client>::size_type
, which is, in all likelihood, an unsigned type. Change the declaration of i
to
std::vector<Client>::size_type i;
Now, you're getting errors in your iterator code because its syntax is incorrect. The for loop should look like this:
for(it = ptr->begin(), it != ptr->end(); ++it) { ... }
You can find the index of the item the iterator is currently pointing at using std::distance
return std::distance(ptr->begin(), it);
Additionally, as mentioned in the comments above, it'd be better to use std::find_if
for this, especially if you have a compiler that supports lambda expressions.
auto it = std::find_if(impl->clients.begin(),
impl->clients.end(),
[&]( Client const& c ) {
return c.getName() == userName;
} );
return (it != impl->clients.end()) ?
std::distance(impl->clients.begin(), it) : -1;
Use this:
int Program::checkClient(string userName)
{
vector<Client> * ptr = &(impl->clients);
vector<Client>::iterator it;
int count=0; //for counting the position
for (it=ptr->begin(); it!=ptr->end(); ++it)
{
++count;
if( (*it).getName() == userName )
{
return count;
}
}
return -1;
}
For searching/finding I prefer using while
, it's easier to understand.
You'd rather use const&
for your method parameter.
So it'd give something like that:
int Program::checkClient(string const& userName) const
{
vector<Client> const& clients = impl->clients;
vector<Client>::const_iterator it = clients.begin();
while (it != clients.end() && it->getName() != userName)
++it;
return it != clients.end() ? it - clients.begin() : -1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.