lower_bound predicate for user defined type

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply ISO 12/16/2008 12:20:34 PM

See related articles to this posting


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
Reply 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
Reply 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
Reply David 12/19/2008 7:05:11 PM
comp.lang.c++.moderated 10664 articles. 10 followers. Post

3 Replies
344 Views

Similar Articles

[PageSpeed] 33


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

User-defined type in user-defined function
I thought this worked for me before ... I am trying to create a function MYTEST.FUNC_UPDATECOORD which has, as one of its parameters, a variable of a type that's defined in the package MYTEST. This results in the error: ERROR at line 7: ORA-06550: line 7, column 32: PLS-00306: wrong number or types of arguments in call to 'FUNC_UPDATECOORD' ORA-06550: line 7, column 21: PL/SQL: ORA-00904: "MYTEST"."FUNC_UPDATECOORD": invalid identifier ORA-06550: line 7, column 5: PL/SQL: SQL Statement ignored which you can see if you cut and paste the following code in SQL P...

User-defined type not defined
Hi: This is all in A97. I'm working with a database that was originally created by someone else, modified greatly by me. Now I'm creating a new version and am more or less starting from scratch, importing objects and rebuilding as I go. Suddenly when I try to compile, I get the message "User-defined type not defined" on the line "dim bkmk as bookmark." Indeed, when I try to use intellisense in dimming a new variable, bookmark isn't on the list. I checked the references, and none are marked missing. I un-checked the dao3.51 ref and re-checked it. I ran re...

User defined type not defined
Hello all, I am trying to write a prog that autamatically sends emails ... Here is what I have done so far In the module section I have put this: Public Function SendEmail(email As String, subject As String, body As String, attach As String) Dim Mail As MailSender Set Mail = New MailSender Mail.Host = "relay.skynet.be" Mail.From = "my.emailaddress@myprovider.be" Mail.AddAddress (email) Mail.subject = subject Mail.body = body Mail.AddAttachment (attach) Mail.Send End Function Then in the program I assign values to the variables email,subject and body Next I call the fun...

User defined type not defined - getting this error yet it is defined in the same module
Hi there, I needed to use some of the functionality of my VB code in my Access program. So I imported all the relevant modules from my VB program into my Access code. (Unfortunately I had not made the relevant code into a class and many of the functions were split over different modules). However, when I go to compile my code in Access, I get a "User defined Type not defined" error, even though the type it is complaining about is defined a few functions above within the same module. I really do not understand this particularly because the code all works fine within VB. Can anyone...

Error: User-Defined Type Not Defined
In A97 on WinXP, I'm trying to use a KB function to provide the next sequential number in a custom counter (a table with two fields-- [NextAvailable] and [FromYear] ). When I run it, I get the "User-defined type not defined" error on the third line of code (Dim rs As ADODB.Recordset) I'm using below: " Function Next_Custom_Counter() On Error GoTo Next_Custom_Counter_Err Dim rs As ADODB.Recordset Dim NextCounter As Long Set rs = New ADODB.Recordset rs.Open "CounterTable", CurrentProject.Connection, adOpenKeyset, adLockOptimist...

User-defined type not defined #3
Hi everyone, I have an error message in an Access 97 database & I was hoping someone may be able to help me get rid of it (bearing in mind I only have an average understanding of Access & absolutely none of VB coding). Originally, this database was in Access 2003 format. I opened it in 2003, then used the convert option to back it down to Access 97. I then opened it in 97. Upon opening, I get this error message: "compile error: user-defined type not defined". When I click ok, I am taken to a screen with a window title of "form_switchboard", with some code in it. &q...

User defined type not defined #2
Hello, I have been working with visual basic for a while but this is something I have never understood. I have some code in a VB6 application that sends email using Winsock and works great. I am trying to incorporate the code in Access 2000 . I inserted the activex control "Microsoft Winsock control (SP6) and it shows up on the form. When I ran the form I get "object variable with block not set" on the line "Winsock1.LocalPort = 0", I added the "Set winsock1 = ActiveXCtl5.Object". Now I get "User defined type not defined." I don't get...

User-defined type not defined #2
How can I trap this error -User-defined type not defined - in order to make custom error messages, when there is a missing reference, or missing dll/ocx file. Siggy Siggy wrote: > How can I trap this error -User-defined type not defined - > in order to make custom error messages, when there is a missing reference, > or missing dll/ocx file. If it's being referenced in a global module it's unlukely that you can since none of the code will compile and run, you get the error before any of the code runs. There was quite a long thread recently about checking for reference...

Compile error: User-defined type not defined
I have a database which compiles. I removed a number of forms, queries, macros, modules and tables from it. When I try to compile the "boiled-down" version, I get an error "User-defined type not defined" at this line: Dim FrmTest as Form_frmHelp I checked the references, all references are identical in both databases. I did a search for Form_frmHelp within the DB and didn't see anywhere that it was referenced. Teh Googles couldn't help me. Anyone got any suggestions? Nevermind. I discovered that somehow the form frmHelp had no code behind it. On...

Type conversion function for user defined type...
I have a question about type conversion function for user defined type. I have two classes class DRect { private : double x0; double y0; double x1; double y1; public : DRect(double a, double b, double c, double d) : x0(a), y0(b), x1(c), y1(d) {} void Union(DRect* p) { x0 = MIN(x0, p->x0); y0 = MIN(y0, p->y0); x1 = MAX(x1, p->x1); y1 = MAX(y1, p->y1); } } class IRect { private : int x0; int y0; int x1; int y1; public : IRect(int a, int b, int c, int d) : x0(a), y0(b), x1(c), y1(d) {} } And I want to do something lik...

Export to Access
Despite having at least 2 days VBA programming experience, this one has got me... I'm trying to export multiple tables into one worksheet in Excel. I've adapted code that I've got from this forum, but I keep getting the "User-Defined type not defined" error on 'Dim objXL As Excel.Application'. Again, from my limited time as a veteran copier, paster and editor, I've had this problem before when using a browse window - which was fixed by downloading the appropriate reference. Can anyone tell me if that is the problem, and if so, where would a fella find such a ...

Compile-error. User defined type not defined?
After following the instructions at http://support.microsoft.com/?id=258049 I get an error at compile time complaining about c As CloseCommand Function InitApplication() '******************************************************************** ' It calls a class module (see Class1 in modules Tab of database ' window) which contains functions to remove the red "X" button ' from the upper right hand corner of the Tow-Pak application. ''******************************************************************** Dim c As CloseCommand Set c = New CloseCommand ...

casting primitive type to user-defined type works in usage
Can anyone kindly explain why the following works, even though it's undoubtedly a very bad thing to do: class Bird { int age; public: Bird(int = 21); void IFly(void); }; Bird::Bird(int lage) { age = lage; } void Bird::IFly() { age = 21; std::cout<<"Bird::IFly"<<std::endl; std::cout<<"age: "<<age<<std::endl; } int main(int argc, char **argv) { int i; Bird *x = reinterpret_cast<Bird*>(&i); x->IFly(); return 0; } PRINTS: "Bird::IFly" "age: 21" xllx.relient.xllx@gmail.com wrote: > ...

mapping betwing a standard type and a user defined type with SWIG
[Note: parts of this message were removed to make it a legal post.] Hello! I've wrote a C library where I redefined (with typedef) the "char" and I gave it the name "my_char". Every things worked well when I gave constant strings to my wrapped functions which takes a "my_char *" as argument (then it is equivalent to give a char * argument). But when I have given a String variable to one of my functions (I initialised a variable var = "" and gave it to the finction), it returned me this: Expected argument 3 of type my_char *, but got String "...

CREATE TYPE containing array of user-defined type elements
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi there! We're trying to create a user-defined type in PostgreSQL 8.2 containing an array of an element whose type is another user-defined one. We're facing a problem here, since when we try to do so: CREATE TYPE newtype AS( x double precision, y double precision ); CREATE TYPE newtype2( INPUT=array_in, OUTPUT=array_out, ELEMENT=newtype ); PostgreSQL complains about non-existent array_out(newtype2). So, we felt into this forum http://osdir.com/ml/db.postgresql.novice/2003-07/msg00147.html and someone sugges...

user defined type
Hello I am writing my own type for use in postgres. I want to be able to save a value - an integer, and a string in this type. I have looked at the documentation for how to do this. The insert into the type works, but when i try to select all from the table, postgres crashes. I don't see what's wrong, so I hope someone can help. thanks -Kjetil the code: typedef struct alignres { int value; char *fstring; }alignres; PG_FUNCTION_INFO_V1(alignres_in); Datum alignres_in(PG_FUNCTION_ARGS) { char *in = PG_GETARG_CSTRING(0); int v; char *first; ...

User Defined Types
Having this form and code in a project I get "only public user defined type in public modules etc....." message * in form Dim Vars() As evVariant Private Sub Command1_Click() mySort (Vars) End Sub Sub mySort(theVars() As evVariant) End Sub * in Types.Bas in same project... Attribute VB_Name = "myTypes" Public Type evVariant vType As String vValue As Integer End Type "Erik Vandamme" <erikvand@iinet.net.au> wrote in message news:4152a18b$0$24411$5a62ac22@per-qv1-newsreader-01.iinet.net.au... > Having this form and code in a project I get "only pu...

User defined type
I am trying to make a user defined type but get the error that it is more than 64K without the lines SgnVideotext As String * 200 SgnVideopath As String * 200 print len(obj) returns the value 25806 and it works fine Adding these two lines causes the error over 64K Any ideas please _________________________________ Option Explicit Type sgndata SgnEvidence As String * 700 SgnExample As String * 700 SgnPicturetext(4) As String * 200 SgnPicturepath(4) As String * 200 SgnVideotext As String * 200 SgnVideopath As String * 200 SgnNextstep As String * 700 End Type Type objectivedata Title As...

HELP !! beginneralert Cannot define Public user defined type within object module
Hi All, After doing a bit of Googleing, i sort of get the impression i'm not the only one doing it right according to books and stuff, but still i am being slowed down in my attempts to quickly master VB by what seems to be a bug. I Get the message Compile Error: Cannot define Public user defined type within an object module. Even when the only code i got is Type Shoe End Type Since i am currently learning visual basic and since i have been doing so for at least 5 days, i am not very experienced (in these type of things) :-) Can somebody tell me how i can continue with my attempts?...

user defined type
Hello I am writing my own type for use in postgres. I want to be able to save a value - an integer, and a string in this type. I have looked at the documentation for how to do this. The insert into the type works, but when i try to select all from the table, postgres crashes. I don't see what's wrong, so I hope someone can help. thanks -Kjetil the code: typedef struct alignres { int value; char *fstring; }alignres; PG_FUNCTION_INFO_V1(alignres_in); Datum alignres_in(PG_FUNCTION_ARGS) { char *in = PG_GETARG_CSTRING(0); int v; char *first; ...

User-defined types
Hello, I'm trying to write a PL/PgSQL function whose sole parameter is an array whose element type is a type that I've created. For example: CREATE TYPE test_type AS (x bigint, y bigint); CREATE OR REPLACE FUNCTION array_test (test_type[]) ... According to the 7.4 docs, "Whenever a user-defined base data type is created, PostgreSQL automatically creates an associated array type, whose name consists of the base type's name prepended with an underscore. The parser understands this naming convention, and translates requests for columns of type foo[] ...

A97: Dim dbs As Database yields error "user-defined type not defined"
I copied the following code snippet from A97 HELP. Am getting an error at compile time suggesting there's a problem with the first line (compile error, user-defined type not defined). It is likely that I've left something out. Doesn't seem to like Dim dbs as Database - that's what's hi-lited after acknowledging the error. Can you see anything wrong with that syntax? Dim dbs As Database, rst As Recordset Dim rstEmployees As Recordset, rstOrders As Recordset Dim rstProducts As Recordset, strSQL As String ' Return reference to current database. Set dbs = ...

checking user defined types
I have defined a class Myclass I instanciate the class and I use it in a function, and I could like check the argument type in the function, but this code don't works func (xMyclass,..): if type(xMyclass) is type(Myclass): ... then I must create a new object of the class and then if type(xMyclass) is type(Myclass()): this solution has the problem when Myclass has a complex constructor. Do you known another solution ? Thanks in advance In article <RmuCc.1142728$A6.4637536@telenews.teleline.es>, "Luis Sol�s" <lsolis@mu.intecsa-inarsa.es> wrote: > I ha...

User-defined type attributes
In light of the recent discussion of formal package parameters, I have been wondering about user-defined type attributes. They don't currently exist in any version of Ada. First, a historical question: Was there a proposal for user attributes that was considered for Ada 2005? My interest in them is akin to my interest in formal package parameters. The prefixed views for functions and procedures (dot- notation) of Ada 2005 are directly analogous to what would be required for attribute syntax. This notation hints at the possibility of a kind of visibility related to formal type paramete...