user-defined iterator

  • Permalink
  • submit to reddit
  • Email
  • Follow


hello All,

I have a simple issue.
I defined a custom container, that encloses a std::list, which in turn
holds objects that are a simple abstraction of a six position array.

Now, i would like to serialize the whole newly-defined container, in
order to copy the contents to another array. So i thought to define an
iterator which represented a "pointer" to the container's data. But,
when i feed these iterators to std::copy the compiler complains about
a lot of types which are defined when a std::iterator is instanced.

the code:

//i leave all unnecessary stuff out just to be clear
#include <list>

using namespace std;

class SixBytes{
public: //i don't trash the example with any accessor methods
        char m_data[6];
};

class MyCont{
        list<SixBytes> m_list;
        public:
        class Iterator{
                const MyCont& m_cont;
                int m_index;
                public:
                Iterator(const MyCont& cnt, int index=0):m_cont(cnt),
m_index(index){}
                Iterator operator++(int){//postfix? just placed this
and the following methods to be "complete"                      //
w.r.t. the requirements of the std::copy algorithm and to this example
                        Iterator ret(*this);
                        m_index++;
                        return ret;
                }
                Iterator& operator++(){//prefix?
                        m_index++;
                        return *this;
                }
                char operator*(){
                        //...return the byte that corresponds to the
position m_
index
                }
        };

        inline Iterator begin() const{ return Iterator(*this); }//the
start of the serialization
        inline const Iterator end() const { return Iterator(*this,
m_list.size()*6); }//it's end
        MyCont(){ m_list.push_back(SixBytes());
m_list.push_back(SixBytes());}
};

int main(){
        char data[13];
        data[0] = 2;
        MyCont m;
        std::copy(m.begin(), m.end(), data+1);
}//example ends here

giving this to the compiler i get this:

/usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
3.4.1/bits/stl_iterator_base_types.h: In instantiation of
`std::iterator_traits<MyCont::Iterator>':
/usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
3.4.1/bits/stl_algobase.h:305:   instantiated from `_OutputIterator
std::__copy_ni2(_InputIterator, _InputIterator, _OutputIterator,
__false_type) [with _InputIterator = MyCont::Iterator, _OutputIterator
= char*]'
/usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
3.4.1/bits/stl_algobase.h:327:   instantiated from `_OutputIterator
std::__copy_ni1(_InputIterator, _InputIterator, _OutputIterator,
__false_type) [with _InputIterator = MyCont::Iterator, _OutputIterator
= char*]'
/usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
3.4.1/bits/stl_algobase.h:358:   instantiated from `_OutputIterator
std::copy(_InputIterator, _InputIterator, _OutputIterator) [with
_InputIterator = MyCont::Iterator, _OutputIterator = char*]'
container.cpp:41:   instantiated from here
/usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
3.4.1/bits/stl_iterator_base_types.h:129: error: no type named
`iterator_category' in `class MyCont::Iterator'

....more ot those errors about value_type and all such things.

Do i have to provide my implementation with these types?
If yes, what about iterator_categoy?
What about the simple char* parameters given to the std::copy
algorithm ? why are they ok?

thank you all,
vasilis.

0
Reply VASILI3000 (7) 6/15/2007 2:18:55 PM

See related articles to this posting


vasili wrote:
> I have a simple issue.

:-)

> I defined a custom container, that encloses a std::list, which in turn
> holds objects that are a simple abstraction of a six position array.
>
> Now, i would like to serialize the whole newly-defined container, in
> order to copy the contents to another array. So i thought to define an
> iterator which represented a "pointer" to the container's data. But,
> when i feed these iterators to std::copy the compiler complains about
> a lot of types which are defined when a std::iterator is instanced.

Since you want to use standard algorithm, it _may_ require that you
specialize 'iterator_traits' for your custom iterator.

>
> the code:
>
> //i leave all unnecessary stuff out just to be clear
> #include <list>
>
> using namespace std;
>
> class SixBytes{
> public: //i don't trash the example with any accessor methods
>        char m_data[6];
> };
>
> class MyCont{
>        list<SixBytes> m_list;
>        public:
>        class Iterator{
>                const MyCont& m_cont;
>                int m_index;
>                public:
>                Iterator(const MyCont& cnt, int index=0):m_cont(cnt),
> m_index(index){}
>                Iterator operator++(int){//postfix? just placed this
> and the following methods to be "complete"                      //
> w.r.t. the requirements of the std::copy algorithm and to this example
>                        Iterator ret(*this);
>                        m_index++;
>                        return ret;
>                }
>                Iterator& operator++(){//prefix?
>                        m_index++;
>                        return *this;
>                }
>                char operator*(){
>                        //...return the byte that corresponds to the
> position m_
> index
>                }
>        };
>
>        inline Iterator begin() const{ return Iterator(*this); }//the
> start of the serialization
>        inline const Iterator end() const { return Iterator(*this,
> m_list.size()*6); }//it's end
>        MyCont(){ m_list.push_back(SixBytes());
> m_list.push_back(SixBytes());}
> };
>
> int main(){
>        char data[13];
>        data[0] = 2;
>        MyCont m;
>        std::copy(m.begin(), m.end(), data+1);
> }//example ends here
>
> giving this to the compiler i get this:
>
> /usr/lib/gcc/i586-mandrake-linux-gnu/3.4.1/../../../../include/c++/
> 3.4.1/bits/stl_iterator_base_types.h: In instantiation of
> `std::iterator_traits<MyCont::Iterator>':
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
That's the implicit specialisation the compiler attempts.  And fails.

> [..]
>
> Do i have to provide my implementation with these types?

Yes, if you want your code to compile.

> If yes, what about iterator_categoy?

Yes

> What about the simple char* parameters given to the std::copy
> algorithm ? why are they ok?

Yes, because the standard library most likely already contains the
specialisation of 'itetator_traits' for built-in pointer types.

V
-- 
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask 


0
Reply v.Abazarov (13255) 6/15/2007 3:02:29 PM

On Fri, 15 Jun 2007 07:18:55 -0700, vasili wrote:
>I have a simple issue.

If it were simple it wouldn't be C++.

>I defined a custom container, that encloses a std::list, which in turn
>holds objects that are a simple abstraction of a six position array.

AFAICS, you want to iterate over the list _and_ the 'six position
array' with a new iterator (not just re-use the
list<SixBytes>::iterator). In this case you need to define your own
iterator with all required typedefs and functions. Look for 'custom
STL iterator', e.g.
http://www.stanford.edu/class/cs107l/handouts/02-Custom-Iterators.pdf
http://www.oonumerics.org/tmpw00/becker.html


-- 
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
0
Reply rpbg123 (870) 6/15/2007 3:15:35 PM

On Jun 15, 5:02 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
> vasili wrote:
> > I have a simple issue.

> :-)

It takes a complicated language to solve complicated
problems:-).

> > I defined a custom container, that encloses a std::list, which in turn
> > holds objects that are a simple abstraction of a six position array.

> > Now, i would like to serialize the whole newly-defined container, in
> > order to copy the contents to another array. So i thought to define an
> > iterator which represented a "pointer" to the container's data. But,
> > when i feed these iterators to std::copy the compiler complains about
> > a lot of types which are defined when a std::iterator is instanced.

> Since you want to use standard algorithm, it _may_ require that you
> specialize 'iterator_traits' for your custom iterator.

He must do something to ensure that iterator_traits<Iterator>
contains the proper typedefs.  The generic implementation of
this template supposes that there are corresponding typedef's in
the Iterator class; the standard library also contains a partial
specialization for pointers (since pointers obviously don't
contain the necessary typedef's).  He can thus either provide a
custom specialization, with the necessary typedef's, or put the
typedef's in his class.  The latter is the classical solution,
and the standard offers a class template, std::iterator, to help
here.  All he has to do is have his iterator derive (publicly)
from the appropriate instantiation of std::iterator, and it
should suffice.

--
James Kanze (Gabi Software)            email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34

0
Reply james.kanze (9769) 6/16/2007 9:18:25 AM
comp.lang.c++ 48332 articles. 29 followers. Post

3 Replies
160 Views

Similar Articles

[PageSpeed] 56


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

User-defined iterator
Object A is composed of a vector of A (itself) and a vector of B. I'm running into difficulties creating an iterator of all the Bs (those contained within the vector of As as well as the vector of Bs.) Somehow I have to maintain the state within the iterator of which A and which B of that A I'm on, but this seems to break the recursive nature of "A is composed of As." [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] jddahl@gmail.com writes: > Object A is composed of a vector of A (it...

Example of a user-defined forward iterator?
Hi, I have an octree class that I would like to (slowly) migrate to an STL-like container. I now need to implement two forward iterators for the class. I would like to use the iterators in the following manner: octree<GLfloat>::nodeIterator p; octree<GLfloat>::itemIterator q; for (p=foo.begin();p!=foo.end();p++) { // bleh } (or something reasonably similar). I have reviewed Stroustrup, but have found the limited examples difficult to adapt to my need. Can anyone provide an example of a simple container and its iterator? Thanks,Brett Brett L. Moore wrote: > Hi,...

Iterate through all members of a user-defined data type?
Hi All, Just wondering if anyone knows if there's a way to iterate through all members of a user-defined data type? I'd like to Debug.Print all values in members of the data type at a point in a subroutine, but it looks so far like i can't do a For Each... or something like mytype(n) etc. Any help appreciated! pt On Aug 19, 9:48 pm, planetthoughtful <planetthought...@gmail.com> wrote: > Hi All, > > Just wondering if anyone knows if there's a way to iterate through all > members of a user-defined data type? > > I'd like to Debug.Print all values ...

[tao-users] Find iterator on an STL container using a IDL defined structure
--_004_1BD1BBDEB9FEE04E8EF927FC69DA3869555A6043FHDP1LUMXC7V42u_ Content-Type: multipart/alternative; boundary="_000_1BD1BBDEB9FEE04E8EF927FC69DA3869555A6043FHDP1LUMXC7V42u_" --_000_1BD1BBDEB9FEE04E8EF927FC69DA3869555A6043FHDP1LUMXC7V42u_ Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable TAO VERSION: 2.0 HOST MACHINE and OPERATING SYSTEM: Linux 2.6.18-238.el5 TARGET MACHINE and OPERATING SYSTEM, if different from HOST: COMPILER NAME AND VERSION (AND PATCHLEVEL): g++ 4.1.2 CONTENTS ...

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...

Memory Difference Between User-Defined Pointer and User-Defined Allocatable
Hello, I have been experimenting with user-defined types recently and come across the allocatable array versus the pointer. To more quickly serve what I'm interested in knowing, here is an example code I wrote: module my_module type my_type integer x_size integer y_size integer z_size double precision, dimension (:,:,:), pointer :: array end type my_type contains subroutine allocate_my_type(this,x,y,z) implicit none type (my_type) :: this integer x,y,z this%x_size = x this%y_size = y this%z_size = z nullify(this%array) allocate(this%arra...

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...

User-Defined and/or User-Triggered Events
Hi, Here I mean "User" in the Programmer or Javascript sense. I merely wish to programmatically trigger an Event. It would be absolutely fantastic if there was a (Form level?) ONUSEREVENT() and a setEvent() function but, in the absence of this, is it not possible to use DOM to change an object's properties resulting in a state-change event? I have tried with ONCHANGE() and that only seems to work if the "interactive" user changes the contents (i.e. document.form.field.value="blah"; does not resuly in an ONCHANGE event. Before I go through each event and prop...

[ace-users] user defined events
Hello, How can I make user defined events and how can I do their event handlers? And how to initiate(fire) this user defined events? thanks, Mohamed shoeb Software Engineer ...

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...

How to define a user defined function in AEL
Dear Cadence, According to the manual, in AEL (Analog Expression Language) there can be user defined functions. I read through the AEL documentation but couldn't find any information on how to define one. I just want to define a function that returns a random number before everytime the simulation runs. Could anybody give me an example or pointer? Thanks, Cao On Thu, 16 Feb 2006 16:24:41 -0600, "Zhiheng Cao" <cao@ece.utexas.edu> wrote: >Dear Cadence, > >According to the manual, in AEL (Analog Expression Language) >there can be user defined functions. I ...

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...

How to define User-Defined Property Mapping File ?
Hi All, I add a property into a path ,Name QQ , Type is string ... I want to stream out and keep the property in the gdsii file,But how .... (I read the transref pdf file , I can't figure out the file syntax ) Thank you, Charley Charley wrote, on 07/15/09 09:11: > Hi All, > > I add a property into a path ,Name QQ , Type is string ... > I want to stream out and keep the property in the gdsii file,But > how .... > (I read the transref pdf file , I can't figure out the file syntax ) > > Thank you, > Charley It seems reasonably clear to me in the documentat...

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...

[tao-users] DII and user-defined exceptions
Hi, Is it possible in TAO to handle user-defined exceptions that are thrown during an invokation when using DII? I tried to call env() in a CORBA::Request object but I discovered that it was deprecated. /Per ...

How can I define a user-defined infix function?
Hi, The following specification never passes Fuzz type-checker, and always prod= uces syntax error: \begin{zed} BOOL ::=3D True | False \end{zed} \syndef{subrel}{infun4}{NewOp=19=1A} \begin{axdef} \_subrel\_ : RELATION \cross RELATION \fun BOOL [at this line] \where \forall R1,R2 : RELATION \\ \t1 @ R1~subrel~R2 =3D True \iff \\ \t2 R1.Att =3D R2.Att \land \\ \t2 R1.Rel \subseteq R2.Rel \end{axdef} while the following does: \begin{axdef} subel : RELATION \cross RELATION \fun BOOL =20 \where \forall R1,R2 : RELATION \\ \t1 @ subel~(R1,R2) =3D Tru...

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 ...

Overhead when deriving a program-defined iterator from std::iterator
When deriving my iterator from std::iterator, I experienced a large increase of its size! On an implementation I'm currently using, the following class (MyIter) has a size of 12! While I would have expected sizeof(MyIter) == 1! class MyIter: public std::iterator<std::bidirectional_iterator_tag, int> { // code declaring ++, etc... char data; }; Still the Draft suggests (or even recommands?) programmers to do so. 24.3.3 2: Typically, however, it would be easier to derive BinaryTreeIterator<T> from iterator<bidirectional_iterator_tag,T,p...

Re: [tao-users] DII and user-defined exceptions
Hi, Please use the PRF form when askign questions See http://deuce.doc.wustl.edu/bugzilla/show_bug.cgi?id=1621 Regards, Johnny Willemsen Remedy IT Leeghwaterstraat 25 2811 DT Reeuwijk The Netherlands www.theaceorb.nl / www.remedy.nl "Per Nyblom" <perny@ida.liu.se> wrote in message news:<200408250706.i7P76P7w002347@portofix.ida.liu.se>... > Hi, > > Is it possible in TAO to handle user-defined exceptions that are thrown > during an invokation when using DII? > > I tried to call env() in a CORBA::Request object but I discove...