473,657 Members | 2,478 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Declaring iterators

I am not sure I quite understand the use of iterators. I have this int
array:

int a[] = {1,2,3,4,5}

I would now like to make an iterator to the first and last element:

std::iterator<i ntiter;
iter = a;

but this does not compile.

If I instead choose to make an iterator on a vector it works:

#include <vector>

std::vector<int vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)?
Apr 28 '07 #1
7 2312
"desktop" wrote:
>I am not sure I quite understand the use of iterators. I have this int
array:

int a[] = {1,2,3,4,5}

I would now like to make an iterator to the first and last element:

std::iterator<i ntiter;
That construct is for the STL and arrays are not part of the STL. If you
want to implement the *properties* of an iterator, go ahead and write one.
But you can't use the one from STL.
iter = a;

but this does not compile.

If I instead choose to make an iterator on a vector it works:

#include <vector>

std::vector<int vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)?

Apr 28 '07 #2
osmium wrote:
"desktop" wrote:
>I am not sure I quite understand the use of iterators. I have this int
array:

int a[] = {1,2,3,4,5}

I would now like to make an iterator to the first and last element:

std::iterator< intiter;

That construct is for the STL and arrays are not part of the STL. If you
want to implement the *properties* of an iterator, go ahead and write one.
But you can't use the one from STL.
Ok so if I want a generic function that works correctly on both int
arrays and vectors, I have to write a new iterator?

How do I check if an iterator has the right type?

I have read that you don't declare an iterator type like Forward, its up
to the function that you implement to make sure that it will satisfy the
properties of a Forward iterator.

That means that it is only by inspecting a function you can see which
iterators are supported. The compiler will not generate any error if I
have an iterator "iter" and then type:

--iter

because you cannot declare a Forward iterator explicitly. Or am I
missing something?
Apr 28 '07 #3
"desktop" writes:
>That construct is for the STL and arrays are not part of the STL. If you
want to implement the *properties* of an iterator, go ahead and write
one. But you can't use the one from STL.

Ok so if I want a generic function that works correctly on both int arrays
and vectors, I have to write a new iterator?

How do I check if an iterator has the right type?

I have read that you don't declare an iterator type like Forward, its up
to the function that you implement to make sure that it will satisfy the
properties of a Forward iterator.

That means that it is only by inspecting a function you can see which
iterators are supported. The compiler will not generate any error if I
have an iterator "iter" and then type:
This will probably not prove helpful but I have the general feeling you are
trying to make a silk purse out of a sow's ear. As I see it you want a
seamless way to handle arrays and vectors. But arrays are not containers.
They are not even classes. Containers have properties like front, back,
size and on and on till the head swims. Arrays don't have those things. If
you want to iterate through arrays, then do so. But it won't be an array
any more because an array doesn't have something as elementary as size
specified. IOW, as I see it, you are on the road to inventing the C++
vector.
Apr 28 '07 #4
On 2007-04-28 21:00, desktop wrote:
osmium wrote:
>"desktop" wrote:
>>I am not sure I quite understand the use of iterators. I have this int
array:

int a[] = {1,2,3,4,5}

I would now like to make an iterator to the first and last element:

std::iterator <intiter;

That construct is for the STL and arrays are not part of the STL. If you
want to implement the *properties* of an iterator, go ahead and write one.
But you can't use the one from STL.

Ok so if I want a generic function that works correctly on both int
arrays and vectors, I have to write a new iterator?
No, you make a parametrized function.
How do I check if an iterator has the right type?
An iterator is not a type, it's a concept. The compiler checks so that
the type you provided fulfils the requirements of the concept.
I have read that you don't declare an iterator type like Forward, its up
to the function that you implement to make sure that it will satisfy the
properties of a Forward iterator.
The compiler does.
That means that it is only by inspecting a function you can see which
iterators are supported. The compiler will not generate any error if I
have an iterator "iter" and then type:

--iter

because you cannot declare a Forward iterator explicitly. Or am I
missing something?
The compiler will refuse to compile the code if the iterator you
supplied does not support the -- operation.
Iterators is an abstract concept that lives in the minds of the
programmers, there is no one type that is an iterator or from which all
iterators inherits. When using iterators the compiler checks so that the
type used as an iterator provides all the functionality required and
will fail to compile the program if it does not. As long as the type
supplied do provide the functionality it *is* an iterator, regardless of
what type it has.

Consider the following code:

#include <numeric>
#include <iostream>
#include <vector>

int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
std::vector<int vec;
vec.push_back(1 );
vec.push_back(2 );
vec.push_back(3 );
vec.push_back(4 );
vec.push_back(5 );

int arrSum = std::accumulate (arr, arr + 5, 0);
int vecSum = std::accumulate (vec.begin(), vec.end(), 0);

std::cout << "Array: " << arrSum << std::endl;
std::cout << "Vector: " << vecSum << std::endl;
}

Here we call the same function (std::accumulat e) with two different
types of iterators, in the first we use int* as iterator and in the
second std::vector<int >::iterator. Those two types have nothing in
common, except that parts of their interfaces are the same: you can
dereference them by using *, you can move them one step forward using
++, and so on. And since they both have the "right" functionality in
their interface we can use them as iterators.

Perhaps it will be easier to understand if I show you how accumulate is
implemented (or rather how I would implement it):

template<class Iter, class Val>
Val accumulate(Iter begin, Iter end, Val v)
{
while (begin != end)
{
v += *begin;
++begin;
}
return v;
}

From this you can see that accumulate places three requirements on the
type used as iterator, you shall be able to test two instance of the
type for inequality (!=), you shall be able to dereference an instance
of the type (*), and you shall be able to increment an instance (++). It
also places one requirement on the type you accumulate the values of,
you shall be able to add-assign (+=).

--
Erik Wikström
Apr 28 '07 #5
"desktop" <ff*@sss.comwro te in message
news:f1******** **@news.net.uni-c.dk...
>I am not sure I quite understand the use of iterators. I have this int
array:

int a[] = {1,2,3,4,5}

I would now like to make an iterator to the first and last element:

std::iterator<i ntiter;
iter = a;

but this does not compile.

If I instead choose to make an iterator on a vector it works:

#include <vector>

std::vector<int vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)
From what Erik says, I gather that int* iter = a; IS an iterator. I.E. You
should be able to pass iter to the standard templates that require an
iterator.
Apr 29 '07 #6
On Apr 28, 8:22 pm, desktop <f...@sss.comwr ote:
I am not sure I quite understand the use of iterators. I have this int
array:
int a[] = {1,2,3,4,5}
I would now like to make an iterator to the first and last element:
std::iterator<i ntiter;
iter = a;
but this does not compile.
Obviously. The template std::iterator requires two arguments,
and doesn't do what you want anyway. (Despite its name, it
isn't an iterator, but simply a convenience class to provide a
certain number of useful typedef's for any iterator you might
choose to define.)
If I instead choose to make an iterator on a vector it works:
#include <vector>
std::vector<int vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)?
Are you saying that if you include <vector>, the line:
std::iterator< int iter ;
compiles? It shouldn't.

Each container type provides its own iterator. Containers in
the STL provide it as a member type (or typedef), e.g.:
std::vector< int >::iterator iter = v.begin();
C style arrays provide it in the form of a pointer; the
constraints on iterators were intentionally designed so that
pointers (into an array) would be iterators. The result is that
you do declare the iterators differently:
std::vector< int >::iterator iter1 ;
int* iter2 ;
What's the problem with that?

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 29 '07 #7
On Apr 29, 2:03 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
"desktop" <f...@sss.comwr ote in message
news:f1******** **@news.net.uni-c.dk...
I am not sure I quite understand the use of iterators. I have this int
array:
int a[] = {1,2,3,4,5}
I would now like to make an iterator to the first and last element:
std::iterator<i ntiter;
iter = a;
but this does not compile.
If I instead choose to make an iterator on a vector it works:
#include <vector>
std::vector<int vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)
From what Erik says, I gather that int* iter = a; IS an iterator. I.E.You
should be able to pass iter to the standard templates that require an
iterator.
That's certainly true.

In this case, the key is to realize that iterator isn't a type,
but a concept. A type (any type) can be used as an iterator if
it meets the constraits. Both std::vector<int >::iterator and
int* meet the constraints of an iterator, so both can be used
anywhere an iterator is required. Neither int nor
std::vector<int meet the constraints, so neither can be used
when an iterator is required. (There is a wierd special case in
the case of things like:
std::vector< int v( 10, 42 ) ;
Formally, function overload resolution results in this calling
the two iterator form of the constructor, with the iterator type
instantiated with int. The standard requires the implementation
to cause the instantiation to behave as if the programmer had
written:
std::vector< int v( static_cast< size_t >( 10 ), 42 ) ;
however. The iterator argument is not considered an iterator.)

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 29 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1610
by: moggous phar | last post by:
how i have to declarate stuff like this: typedef struct { PfadIter Parent; CString Name; } PFADSTRUCT; typedef PfadMapType::iterator PfadIter; typedef std::map<PFADSTRUCT, int> PfadMapType; is there any uncomplete decl like
18
2290
by: deancoo | last post by:
I have gotten into the habit of often using copy along with an insert iterator. There are scenarios where I process quite a lot of data this way. Can someone give me a general feel as to how much of a performance hit I'm taking using this technique versus using 'copy' to copy directly into a container with elements in place? Thanks, d
3
2915
by: codefixer | last post by:
Hello, I am trying to understand if ITERATORS are tied to CONTAINERS. I know the difference between 5 different or 6(Trivial, on SGI). But what I fail to understand is how can I declare all 5 kinds of iterators on say a vector. OR is it that any iterator declared on Vector is Random Iterator which has the functionality of all the others.
24
3943
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = s2 = s3 = for value in ???(s1, s2, s3):
8
2574
by: Steve Lambert | last post by:
Hi, I'd be grateful if someone could clarify this for me. In the linked list structure my intention is to declare an array of length 3 containing pointers to node eg. Node *Iterators The compiler seems to interpret this as a pointer to an array of 3 nodes instead. This interpretation ensures that the second assigment to mynode below fails compilation with the given message.
2
2339
by: ma740988 | last post by:
typedef std::vector < std::complex < double > > complex_vec_type; // option1 int main() { complex_vec_type cc ( 24000 ); complex_vec_type dd ( &cc, &cc ); } versus
90
3410
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
11
4754
by: Jim Michaels | last post by:
friend fraction& operator+=(const fraction& rhs); fraction.h(64) Error: error: 'fraction& operator+=(const fraction&)' must take exactly two arguments I practically pulled this out of a C++ book (except for the "friend"). can someone explain why GCC is giving me problems here? for a += or similar operator, what does a proper declaration look like and what are its arguments for?
18
2108
by: desktop | last post by:
1) I have this code: std::list<intmylist; mylist.push_back(1); mylist.push_back(2); mylist.push_back(3); mylist.push_back(4);
0
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.