lower_bound predicate for user defined type

I would like to use lower_bound version with predicate on container
with user defined type. The problem is that my predicate isn't
comparing two user defined types, but one user defined type and one
built in type. Note that predicate knows how to compare these two.
Here is a code to demonstrate my problem:

struct FirstLast
{
	FirstLast(size_t first, size_t last) : first(first), last(last) {}

	size_t first;
	size_t last;
};

std::vector<FirstLast> vec;

vector is sorted using predicate:

struct CompareByLast : std::binary_function<bool, FirstLast,
FirstLast>
{
	bool operator()(const FirstLast& left, const FirstLast& right) const
	{
		return left.last < right.last;
	}
};

I try to use lower_bound like this:

size_t val = 4;
std::vector<FirstLast>::const_iterator iter = std::lower_bound
(vec.begin(), vec.end(), val, FindByLast());

struct FindByLast : std::binary_function<bool, FirstLast, size_t>
{
	bool operator()(const FirstLast& left, size_t right) const
	{
		return left.last < right;
	}
};

the error I get is:

error C2664: 'bool FindByLast::operator ()(const FirstLast &,size_t)
const' : cannot convert parameter 1 from 'const size_t' to 'const
FirstLast &'
           Reason: cannot convert from 'const size_t' to 'const
FirstLast'
          No constructor could take the source type, or constructor
overload resolution was ambiguous
          \include\algorithm(2300) : see reference to function
template instantiation 'bool std::_Debug_lt_pred<_Pr,FirstLast,_Ty>
(_Pr,_Ty1 &,const _Ty2 &,const wchar_t *,unsigned int)' being compiled
          with
      [
              _Pr=FindByLast,
              _Ty=size_t,
              _Ty1=FirstLast,
              _Ty2=size_t
          ]
          include\algorithm(2314) : see reference to function template
instantiation '_FwdIt
std::_Lower_bound<std::_Vector_iterator<_Ty,_Alloc>,unsigned int,__w64
int,_Pr>(_FwdIt,_FwdIt,const unsigned int &,_Pr,_Diff *)' being
compiled
          with
      [
 
_FwdIt=std::_Vector_iterator<FirstLast,std::allocator<FirstLast>>,
              _Ty=FirstLast,
              _Alloc=std::allocator<FirstLast>,
              _Pr=FindByLast,
              _Diff=__w64 int
          ]
          projects\lowerbound\lowerbound.cpp(22) : see reference to
function template instantiation '_FwdIt
std::lower_bound<std::_Vector_iterator<_Ty,_Alloc>,size_t,FindByLast>
(_FwdIt,_FwdIt,const unsigned int &,_Pr)' being compiled
          with
      [
 
_FwdIt=std::_Vector_iterator<FirstLast,std::allocator<FirstLast>>,
              _Ty=FirstLast,
              _Alloc=std::allocator<FirstLast>,
              _Pr=FindByLast
          ]

STL implementation is calling predicate with Predicate(FirstLast,
size_t) and Predicate(size_t, FirstLast) but defining one more operator
() in my predicate doesn't help.

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
ISO
12/16/2008 12:20:34 PM
comp.lang.c++.moderated 10706 articles. 11 followers. allnor (8507) is leader. Post Follow

3 Replies
425 Views

Similar Articles

[PageSpeed] 54
On Dec 16, 1:20 pm, Nikola Smiljani� <popiz...@gmail.com> wrote:
>
<snip>
> struct FirstLast
> {
>         FirstLast(size_t first, size_t last) : first(first), last(last) {}
>
>         size_t first;
>         size_t last;
>
> };
>
<snip>
>
> I try to use lower_bound like this:
>
> size_t val = 4;
> std::vector<FirstLast>::const_iterator iter = std::lower_bound
> (vec.begin(), vec.end(), val, FindByLast());
>
This is your first problem. Lower doesn't want val(size_t) it wants val
(FirstLast). You would need to define
FirstLast val(0,4);

> struct FindByLast : std::binary_function<bool, FirstLast, size_t>
> {
>         bool operator()(const FirstLast& left, size_t right) const
>         {
>                 return left.last < right;
>         }
>
> };
>

This is your second problem. Your third template parameter needs to
changed from size_t to FirstLast. Then the operator() needs it's third
type to be const FirstLast &.

HTH


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
mzdude
12/16/2008 5:29:20 PM
On Dec 16, 1:20 pm, Nikola Smiljani� <popiz...@gmail.com> wrote:
> I try to use lower_bound like this:
>
> size_t val = 4;
> std::vector<FirstLast>::const_iterator iter = std::lower_bound
> (vec.begin(), vec.end(), val, FindByLast());
>
> the error I get is:
>
> error C2664: 'bool FindByLast::operator ()(const FirstLast &,size_t)
> const' : cannot convert parameter 1 from 'const size_t' to 'const
> FirstLast &'
>            Reason: cannot convert from 'const size_t' to 'const
> FirstLast'

start with:

http://www.sgi.com/tech/stl/StrictWeakOrdering.html

the first argument type and second argument type of a
StrictWeakOrdering function object must be the same.

the compiler is trying to convert the second one (std::size_t) to your
FirstLast.
for your simple example, just add a conversion constructor to
FirstLast and you should be golden:

FirstLast::FirstLast( std::size_t first )
   : first( first ), last( last ) { }

do not make it explicit so FirstLast can be created from a single
size_t arg.

you might also want to derive from appropriate binary function
respecting the concept checks on StrictWeakOrdering:

struct FindByLast
   : std::binary_function<bool, FirstLast, FirstLast> { ... };

I have attached a fully functional example with these modifications,
please look at it below to see the corrected code.

however, I'd like to mention that often in real world programming you
need a more flexible approach than just conversion constructors.

I have implemented complex and generic run time (as in built by users
at run time) predicates and I can show you the door.
for starters just think on using external polymorphism or a simple
holder like boost::any.

for more advanced things (like binding predicates on custom data and
constraints using arbitrary argument lists to binary
StrictWeakOrdering predicates according to a set of intersection
policies) I suggest you use for starters boost::tuple as second
argument and provide a facet based on a given intersection policy (or
set of policies) to a StrictWeakOrdering.

imagine this:

template< class Constraint > class Base {
   Constraint constraint( ) const;
};

template< class Data > struct ByLast
   : std::binary_function< bool, boost::any, boost::any > {
   typedef typename base_traits< Data >::base_type base_type;
   typedef typename base_traits< Data >::constraint_type
constraint_type;
   bool operator ()( const boost::any & a, const boost::any & b ) {
     return ( boost::any_cast< base_type >( a ) ).constraint( )
          < ( boost::any_cast< constraint_type >( b ) );
   }
};

note how knowing the Base data type (that actually spawns different
hierarchies of data types based on constraint type) and assuming Data
is convertible to Base you can manipulate any kind of Data that
matches the Base interface with any kind of constraint by delegating
the operator (the less than above) to Constraint type. Data doesn't
need to know how Constraints are compared but it just needs to
implement a constraint() method to show a Constraint type. of course
the operator itself can become a template argument etc.

anyway, good luck.

gil

/*
  * lower_bound.cpp
  *
  *  Created on: Dec 16, 2008
  *      Author: vnicula
  */

#include <functional>
#include <iostream>
#include <vector>
#include <iterator>

struct FirstLast {
   FirstLast(size_t first, size_t last)
     : first( first ), last( last ) { }

   FirstLast( std::size_t first )
     : first( first ), last( last ) { }

   friend std::ostream & operator <<(
     std::ostream & o,
     const FirstLast & f
   ) {
     return o << "( " << f.first << ", " << f.last << " ) ";
   }

   size_t first;
   size_t last;
};

struct CompareByLast
   : std::binary_function< bool, FirstLast, FirstLast > {
   bool operator ()(
     const FirstLast& left,
     const FirstLast& right
   ) const {
     return left.last < right.last;
   }
};

struct FindByLast
   : std::binary_function<bool, FirstLast, FirstLast> {
   bool operator ()(
     const FirstLast& left,
     const FirstLast& right) const {
     return left.last < right.first;
   }
};

int main( ) {
   std::size_t val = 4;
   std::vector< FirstLast > vec;

   for ( int i = 1; i < 20; i++ ) {
     vec.push_back( FirstLast( i, ( i - 10 ) * ( i-10 ) ) );
   }

   std::sort( vec.begin( ), vec.end( ), CompareByLast() );
   std::cout << "Sorted vector:" << std::endl;
   std::copy(
     vec.begin( ),
     vec.end( ),
     std::ostream_iterator< FirstLast >( std::cout )
   );
   std::cout << std::endl;

   std::vector< FirstLast >::const_iterator iter
     = std::lower_bound( vec.begin(), vec.end(), val, FindByLast() );
   if ( iter != vec.end( ) ) {
     std::cout << "Lower bound with "
               << val
               << " is:"
               << *iter
               << std::endl;
   } else {
     std::cout << "Logic error: couldn't find lower bound with "
               << val
               << "."
               << *iter
               << std::endl;
   }

   return EXIT_SUCCESS;
}


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Gil
12/16/2008 5:30:57 PM
on Tue Dec 16 2008, Gil <ivnicula-AT-yahoo.com> wrote:

> On Dec 16, 1:20 pm, Nikola Smiljanić <popiz...@gmail.com> wrote:
>> I try to use lower_bound like this:
>>
>> size_t val = 4;
>> std::vector<FirstLast>::const_iterator iter = std::lower_bound
>> (vec.begin(), vec.end(), val, FindByLast());
>>
>> the error I get is:
>>
>> error C2664: 'bool FindByLast::operator ()(const FirstLast &,size_t)
>> const' : cannot convert parameter 1 from 'const size_t' to 'const
>> FirstLast &'
>>            Reason: cannot convert from 'const size_t' to 'const
>> FirstLast'
>
> start with:
>
> http://www.sgi.com/tech/stl/StrictWeakOrdering.html
>
> the first argument type and second argument type of a
> StrictWeakOrdering function object must be the same.

That's no longer exactly current.  It depends whether your 
implementation is
keeping up with the times, but see
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2495.html#270

FWIW'ly,

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
David
12/19/2008 7:05:11 PM
Reply:
Similar Artilces:

Prevent User from Answering Message on OUTQ
I work for an organization that allows the users to answer messages for a spool file, e.g. Verify Alignment, that isn't theirs. This is necessary due to the way they print a particular spool file. This is all well and good for any OUTQ except one. I would like to prevent them from answering messages. I have a test user setup with *JOBCTL special authority(don't ask). I have changed the OUTQ so Operator Controlled is *NO. If the spool file is on hold, they can't release it or view it. If the spool file is ready, they can't view it or put it on hold. However, they can sti...

[tao-users] new user corba arch question
Hi, if allowed, would like to ask a general corba question: I would like to be able to a) start up a server with pull of threads b) receive a requst to do asynch work (from client) c) respond saying: I got the request d) do the work now in a separate thread within the same serverant e) optionally call the client via call back saying I am done: I have conceptual difficulty understanding how to do c) and d) decoupled that is 'reply that request is received' and submit request for processing in another 'worker thread' for the same server. I searched the ...

how do I retrieve initFcn user variables
Hello again, I'm using initFcn callbcak function in my simulink model. Amongst others I'm defining model variables which set the appropriate model blocks parameters. For example: f=450 sets the PWM GEN block carrier frequency to 1050Hz. I want to know how can I query simulink model in order to retrieve this variable programmatically. I tried to use get_param() but couldn't do the trick. This way I only get the parameter/variable name. >> get_param([bdroot '/PWM GEN'], 'Fc') ans = f Any suggestions? K Once you know the name of the variable...

reading 'type' from eventhandlers
I'm looking through the client side javascript reference and there's some mighty useful information in here, but it is not very specific on 'reading' information from event handlers. In the interest of streamlining my scripting, I was thinking I could write multi-purpose functions to handle mouseOver and mouseOut events. Thus far, I am manually passing if it is an Over or Out event, but it occurs to me that there might be a way to read status of an event somewhere. Alas, the web is so full of 'simple' mouseOver and mouseOut handling, I have not as of yet refined a se...

How do Mac users uncompress Installshield .cab files?
I'm asking this for a newsgroup-phobic Mac-using friend :)... Are there any Mac OSX resources for unarchiving Windows Installshield ..exe files (and internal cab files). I realize that there's probably not alot of demand for extracting Installshield files under OSX, since the presumption is that those files would be installed on a Windows system. But, he would like access to some Mac & Windows fan-created game resources that are bundled with Installshield, that, once unbundled, will work under OSX. It's getting them out of the archive that's the only issue. "cabextr...

[News] Former Vista Users User Chooses XP Over Vista?
Hey, I Just Bought a Windows XP PC! ,----[ Quote ] | I've been running Vista, in one form or another, on my work desktop | since August of 2005. But that machine, which is a few years old, | is a tolerable Vista machine at best. This HP has more than enough | horsepower for Vista...and if it serves me as long and as well as | the Compaq it's replacing, I'll be very happy. `---- http://blogs.pcworld.com/techlog/archives/003752.html 'Go Beyond Vista' ,----[ Quote ] | Apple has started the rumored Vista countermarketing campaign in | its company stores. `---- http://www.m...

Question about lower_bound
On page 181 of Effective STL, it said 'It 's knowning when equal_range is a better way to search than lower_bound, knowing when lower bound is preferable to find..." My question is understand what situation is lower_bound is better than find? I think both algorithm stops when it find the first item which matches the condition. So they should be the same, right? Thank you for any help. Allerdyce.John@gmail.com wrote: > On page 181 of Effective STL, it said 'It 's knowning when equal_range > is a better way to search than lower_bound, knowing when lower bound is ...

[tao-announce] Any users of the ACE/TAO HP NSK port?
Hi, Several years ago HP did a port of ACE/TAO to the HP NSK v2 and v3 versions. We are considering of removing support for NSK v2/v3 because that would cleanup a lot of code in ACE. Are there any users that use ACE/TAO on HP NSK, if so, let us know, else we will remove the HP NSK v2/v3 ports. Best regards, Johnny Willemsen ...

howto limit from only to authorized user? (2)
Hello, I'v sendmail 8.12.x I would want to limit the From (for which my sendmail is relay) address only for authorizzed users that use ssl (startls+login or plain) how to do? thnx a lot (again). On Thu, 5 Feb 2004, francesco defilippo wrote: > Hello, I'v sendmail 8.12.x I would want to limit the From (for which my > sendmail is relay) address only for authorizzed users that use ssl > (startls+login or plain) how to do? Something like the following (in your mc file) might do what you want: define(`confAUTH_OPTIONS',`A,p,y')dnl -- Weldon Whipple weldon@whipple.or...

problem adding users
I just installed Solaris 10 and am having a problem with adding users. I invoked the command "useradd -d /home/doc -m -s /bin/zsh -c "Doctor Z2A" doc" and it spits out the error: "UX: useradd: ERROR: Unable to create the home directory: Operation not applicable.". I looked around a bit and I think that I have to edit /etc/auto_home but I'm not entirely sure and I don't know how I would edit it. Can anyone help me out? DocZ2A@gmail.com wrote: > I just installed Solaris 10 and am having a problem with adding users. > I invoked the command "use...

Southampton Acorn Users Group
The next meeting of the Southampton Acorn Users Group will take place on Tuesday June 8th, at Itchen College, Middle Road, Bitterne, Southampton, from 19:00 until 21:00. We will be in room S1. Admission is GBP1 and all are welcome. There will be at least one BeagleBoard and one Iyonix to look at and play with. Dave ...

Re: [ace-users] ACE_Reactor and handle_timeout method #2
Thanks for the PRF! <ygor@comcast.net> wrote in message news:<200309291835.h8TIZUpb018612@cliff.cse.wustl.edu>... > ACE VERSION: 5.3.1 > > HOST MACHINE and OPERATING SYSTEM: Red Hat 7.1 > TARGET MACHINE and OPERATING SYSTEM: Same > CONTENTS OF $ACE_ROOT/ace/config.h: config-linux.h > CONTENTS OF $ACE_ROOT/include/makeinclude/platform_macros.GNU: > platform_linux.GNU > > AREA/CLASS/EXAMPLE AFFECTED: > ACE_Reactor and handle_timeout method > > DOES THE PROBLEM AFFECT: > EXECUTION? > > SYNOPSIS: > "handle_timeout" does...

giving access on a subset of data filtered by user login?
Hi all, I created a database application, and created the protection setup, with users and grants. I have this problem: I would like to filter/give access & grants on a particular subset of data, on the basis of the user logged in. In other words, say you have a table with a field containing a value, I would like a particular user who logs in to see modify and delete only his own data subset, identified by a value in that field for example (or in a different way, as long as I can filter). The user should always be able to insert data. It is possible to build up such a "filtered acce...

MMDF Retired Users mail stock
OS: unix 5.0.5 How Can I get rid of messages waiting on the mail spooler (q.local) for users that have a valid login but they were retired and now the description for those logins is '*RETIRED' ? I guess the unix accepts the emails for those users because they exist on the /etc/passwd file but because they are retired then the unix won't deliver them . Please help. Regards, In article <22edc.19741$So1.2545@newssvr27.news.prodigy.com>, corrlens <askme@later.com> wrote: >OS: unix 5.0.5 > >How Can I get rid of messages waiting on the mail spooler (q.local)...

Multiple users on same file
In SW can more than one user work on an assembly file and a part file at the same time?. Yes, but the last one to save wins! The FILE/RELOAD command is very handy as is having the options OPEN REFERENCED DOCS READONLY and DON'T PROMPT TO SAVE READ ONLY DOCUMENTS. You check the first so as not to lock everyone out of documents you are not intending to change and you check the second to prevent overwriting others work and keep you out of SAVEAS hell. The discipline part is that you have to remember to uncheck READONLY in the RELOAD command and then reload the document before changing any...

newbie q: how to let a user kill another user's process?
hi all! how you could help me with this newbie problem: user A needs to kill user B's processes. neither are root. normal executing gives 'not owner'. thanks! -Bassarabbas On Mon, 24 Nov 2003 10:27:12 +0100, "bass A" <hotletter@spammail.com> wrote: >hi all! how you could help me with this newbie problem: > >user A needs to kill user B's processes. neither are root. normal executing >gives 'not owner'. > >thanks! > >-Bassarabbas There is no straightforward way to do this in Solaris, but you have a couple of options. I'...

Any ACL2 users out there?
Is anyone reading this newsgroup using ACL2 (the theorem prover, not Allegro Common Lisp 2 (there is no such thing))? I'm trying to learn how to use it, and the documentation is pretty good, but it would be handy to be able to ask some questions of an experienced user. Thanks, Ron Garret ron.garret@jpl.nasa.gov Ron Garret wrote: > Is anyone reading this newsgroup using ACL2 (the theorem prover, not > Allegro Common Lisp 2 (there is no such thing))? I'm trying to learn > how to use it, and the documentation is pretty good, but it would be > handy to be able to a...

Netatalk+Mysql user Authentication
Hello, I have created a user database in Mysql to work with proftpd, and it work really good. The reson are that I don't want any FTP-Users to have a shell account, and it easyer to handle the users from a webpage. My question is, work this for Netatalk (1.6.3-3). So my MacIntosh users can login with user Mysql-Authentication. Thanks for your help Sorry for my bad english grammar. :-) / Daniel ...

Vector division was defined.
Vector by vector division was defined. Please refer to my posting: <http://groups.google.com/group/sci.physics.relativity/msg/36e6ef708920b141?dmode=source> ...

Quantified expressions: no support for restriction predicates
I read the discussion in AI-0176 a while ago and could not see any consider= ation given to supporting 'restriction predicates' in quantified expression= s. It is not uncommon for logic notations used in computer science/formal = methods to allow a predicate following a vertical bar to restrict the value= s over which the bound variable is quantified, e.g. =E2=88=80 X : T | Even(X) =E2=88=99 P(X) -- P(X) is true for all even X = in T =E2=88=83 X : T | Odd(X) =E2=88=99 Q(X) -- Q(X) is true for any odd X i= n T For example, see [1, 2, 3] (references at the bottom). (Note that...

The Truly Clueless Ubuntu 11.04 Nappy User....
This must be Jeb screwing around with us.... http://ubuntuforums.org/showthread.php?t=1742034 "Please i am beginner i just installed squid please explain" The next guy writes: "Re: squid cache size Explain what?" Bwaaaaaaaaaaaaaaaaaa!!!!! -- flatfish+++ Please visit our hall of Linux idiots. http://linuxidiots.blogspot.com/ Watching Linux Fail: http://limuxwatch.blogspot.com/ Desktop Linux: The Dream Is Dead "By the time Microsoft released the Windows 7 beta in January 2009, Linux had clearly lost its chance at desktop glory." http://www.pcworld.com/...

OS X Tiger
Ok, so I resurrected an old G4 to make pdfs, and installed Tiger on it. The idea being that we can pop out proof pdfs, and the sales types can log into it, grab the pdf and e-mail it. Hit one little snag here, it looks like I can only have a maximum of 10 users logged into Tiger with the native file sharing stuff, and, of course I need to get about 13 or so on at the same time. I'm really not about to go buy specific server software just to get my pdfs out...any suggestions, anyone? KCP.... In article <powell_on_tour-422C45.21061125082005@news.sentex.ca>, K P <powell_on_...

[ace-users] tests/
------=_Part_271120_25293601.1177947507718 Content-Type: multipart/alternative; boundary="----=_Part_271121_8466064.1177947507718" ------=_Part_271121_8466064.1177947507718 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi evryone I did not understand the operation of Main.cpp in the test programs in /tests, is it possible to have a main methode for each program, if yes so how? I want to use just one program of this programs and i don't know how to do Thank you in advance ------=_Part_...

windows users are probably unaware of just how far behind they are
so i'm copying archive backups from a debian box to a win2k server. and at some point obviously this would fill up the destination server. so - i want a simple script on the windows box to delete directories older than a few of weeks - this means that the user can copy the files to DVD but there is a safety net stopping the server from filling up and crashing. this is not actually possible - even on the 'advanced' windows 2003!!! the best solution is to install gnu utilities for win32 (OSS saves the amateurs again) - or a 3rd party utility like fsince. and don't even get m...

individual DEFINE file in DC
I put my DEFINE in an individual file. Simulation is OK. But how to deal with it in DC? Thanks in advance. concatenate your "read_verilog" into a single statement. ie. read_verilog {define.v one.v two.v three.v} instead of read_verilog define,v read_verilog one.v read_verilog two.v etc Mike <mpub@sohu.com> wrote in message news:1106796507.300663.263640@c13g2000cwb.googlegroups.com... >I put my DEFINE in an individual file. Simulation is OK. > But how to deal with it in DC? > > Thanks in advance. > Thanks a lot. It works ...