alphasierra
alphasierra

Reputation: 149

std::find conditional statement not working as expected

So I'm trying to write a loop with a conditional statement that compares the member of a struct, and if the member value matches the requirement outputs some data.

The structs are stored in a vector that an encapsulating for loop iterates through using const_iterator usersInItr. The struct contains a string for the username, and a string vector for the groups of type std::vector<std::string> groups.

This is the specific part of the code being troublesome:

//Look for member group to proceed with output
if(*std::find(usersInItr->groups.begin(),usersInItr->groups.end(),"member")=="member")
{    
    ConfigFile << usersInItr->username << std::endl;
}
else
{
    std::cout << "Nope" << std::endl;
}

The idea being that the std::find statement searches through the group string vector of each user structure to check if it contains the string "member". From what I understand from the documentation, std::find will return an iterator which points at the index that contains the member, or if not found just the last item in the container. So I dereference the iterator from the std::find function and check to see if it matches.

However it does not work. When the groups vector does not contain a "member" entry the TRUE branch still runs. I tried outputting the statement on its own:

std::cout << *std::find(usersInItr->groups.begin(),usersInItr->groups.end(),"member") << std::endl;

It always outputs "member", even when the groups string vector doesn't contain the term...so I'm not sure what's going on here. From my understanding of the function this should work.

Thanks!

Upvotes: 0

Views: 640

Answers (2)

moses.nebogipfel
moses.nebogipfel

Reputation: 61

By the way which operations on groups vector do you do more often? I suspect that testing that user is member of the some group. I just curious that in yours case the set of string is better solution. In my opinion testing existence of element in set is more comfortable than other containers and its complexity is better than find operation on vector. Of course for quick searching you must pay by slower insertion.

std::set<std::string> s;
s.insert( "some group" );
s.insert( "member" );
s.insert( "another group" );

if( s.count( "member" ) > 0 )
  std::cout << "Yes";
else
  std::cout << "No";

For more details please refer http://www.cplusplus.com/reference/set/set/

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

The iterator returned from std::find will point "item" just past of the last item, not the last item, so do not dereference it without checking.

To see if an item was found, you should write like this:

if(std::find(usersInItr->groups.begin(),usersInItr->groups.end(),"member") != usersInItr->groups.end())
{    
    ConfigFile << usersInItr->username << std::endl;
}
else
{
    std::cout << "Nope" << std::endl;
}

Upvotes: 2

Related Questions