troubleshooting Question

binary_search of a vector of structures: Windows compilation failure!

Avatar of mrwad99
mrwad99Flag for United Kingdom of Great Britain and Northern Ireland asked on
C++
12 Comments1 Solution455 ViewsLast Modified:
Ah hello.

I am trying to carry out a binary search of a vector of structures.  The following code demonstrates my problem, which I have acquired from http://rdsrc.us/yDkZPv.

#include <algorithm>
#include <vector>
#include <string>

using namespace std;

struct Human
{
	std::string name;
};

struct Comparator
{
   bool operator() ( const Human& lhs, const std::string& rhs )
   {
      return lhs.name < rhs;
   }
   bool operator() ( const std::string& lhs, const Human& rhs )
   {
      return lhs < rhs.name;
   }
};

int main(int argc, char * argv[])
{
	std::vector<Human> vec;
	std::string nameToFind = "ss";
	binary_search( vec.begin(), vec.end(), nameToFind, Comparator() );

	return 0;
}

Open in new window


Now, on the linked SO question, the author states that it solved his problem.  However, on my VS2008, the code complains (works fine on Solaris):

bool Comparator::operator ()(const std::string &,const Human &)' : cannot convert parameter 1 from 'Human' to 'const std::string &'

I think this is a "feature" of the MS implementation of the STL...can anyone suggest a way to achieve this search so that it works on Windows please?

TIA
ASKER CERTIFIED SOLUTION
phoffricSoftware Engineering and Matlab Analyst

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros