473,508 Members | 2,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

index vs iterator

I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.
Feb 1 '06 #1
13 13371
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.


A pair of iterators designates a sequence of elements. One way to get a
pair of iterators is to use a container that holds actual elements, but
there are other ways. For example, an input stream reading a file that
holds text representations of integer values can be treated as a
sequence of integer values by using two istream_iterator<int> objects.
Once you have that pair of iterators you can pass them to standard
algorithms, so you don't have to rewrite the code, for example, to copy
the contents of one sequence into another.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Feb 1 '06 #2
"Chameleon" <ch******@hotmail.NOSPAM.com> wrote in message
news:dr**********@volcano1.grnet.gr...
:I am programming in C++ for 4 years, so I am not a newbie but I am not a
: very experienced programmer on standard C++ libary.
:
: My question is this:
:
: Can you tell me one case which an iterator is better than index?
:
: For me (until now) iterators are very strangely objects because they are
: useless for me.
: But since most of members of containers use iterators, I am stumped.
:
: I think, for using vector & map, index is far more useful than iterator.

An index only can be used for containers that (efficiently) support random
access (i.e. direct access to an element at a given position).
An iterator is a more general concept. Iterators offer efficient traversal
of linked lists, files, and a number of other data structures. It often
leads to the generation of more efficient code.

Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Feb 1 '06 #3

Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?
The first case that springs easily to mind is that all the standard
library algorithms use iterators.
For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.


If all you ever do with them is read and write individual elements
using operator[] then maybe iterators don't add much value. But that's
a small subset of what containers, iterators and algorithms can do for
you.

Gavin Deane

Feb 1 '06 #4

Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.


Until you decide that your storage should be a different container and
your use of index now requires a rewrite of all your loops.

Feb 1 '06 #5
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.
What book are you reading to correct that? I recommend N. Josuttis, "The
C+++ Standard Library".
My question is this:

Can you tell me one case which an iterator is better than index?
In the cases where index is not available (like with 'std::list', for
example). In the case where a generic function accepting an iterator
is called. When writing a function template that is supposed to work with
more than one container type.
For me (until now) iterators are very strangely objects because they are
useless for me.
They exist to create _uniformity_ among all containers and ability to use
all containers' iterators as well as regular pointers in all standard
algorithms.
But since most of members of containers use iterators, I am stumped.
Stumped? You may even be more stumped if I tell you that most standard
algorithms use iterators. I guess you never ventured so far into C++...
I think, for using vector & map, index is far more useful than iterator.


Yes. Are those two containers the extend of the standard library you've
ever used? Are you saying you never attempted to use 'set' or 'list'?

V
--
Please remove capital As from my address when replying by mail
Feb 1 '06 #6
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.


Only for std::vector does an index feature any kind of advantage: you can do
arithmetic on indices and use stuff like 2*i+1 to iterate over the
odd-index elements. However with, for instance std::map< string, data >,
indices will not allow you to iterate through the map in any meaningful
way.

Also, iterators provide a *unified* way of accessing elements. Think of
using indices to access elements of a list: the runtime overhead will just
suck. Iterators decouple algorithms from containers. If you start using
algorithms from the library, you will grow to like iterators.
Best

Kai-Uwe Bux
Feb 1 '06 #7
Victor Bazarov wrote:
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not
a very experienced programmer on standard C++ libary.


What book are you reading to correct that? I recommend N. Josuttis, "The
C+++ Standard Library".


I readed in the past "Thinking in C++" vol.1 and a big part of vol.2
I think, for using vector & map, index is far more useful than iterator.


Yes. Are those two containers the extend of the standard library you've
ever used? Are you saying you never attempted to use 'set' or 'list'?

yes
Feb 1 '06 #8
Chameleon wrote:
Victor Bazarov wrote:
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am
not a very experienced programmer on standard C++ libary.

What book are you reading to correct that? I recommend N. Josuttis, "The
C+++ Standard Library".

I readed in the past "Thinking in C++" vol.1 and a big part of vol.2


Well, learning about the differences or advantages is useful since it does
give you an opportunity to evaluate (or revisit) your implementation. I
strongly recommend taking a read of the "Effective" series by Meyers and
thinking of getting the Josuttis book.
I think, for using vector & map, index is far more useful than iterator.

Yes. Are those two containers the extend of the standard library you've
ever used? Are you saying you never attempted to use 'set' or 'list'?


yes


Well, lucky you, then. If whatever you do never leads you to the need
to choose more carefully, weighing the pro and con of different standard
containers, your life is simple. Simple is good. As one says, if the
shoe fits...

V
--
Please remove capital As from my address when replying by mail
Feb 1 '06 #9
Chameleon wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator


ignoring container types that do not support random access (list, set,
etc.), iterators still offer:

- pointer like semantics (think of string::iterator vs char*)
- generalized concept usable beyond iteration over elements inside a
container
- semi-container-independend way to access elements (whatever scott
meyers tells you otherwise :)
- better performance than container member functions in a few cases
- etc.

whenever you would like to utilize one of the above you might think
about using iterators instead of member functions.

try to implement the following examples without iterators:

// convert string to upper case
std::string s("hello world");
std::transform(s.begin(), s.end(), s.begin(), toupper);

// reverse any map
template <typename MapT>
std::multimap<typename MapT::mapped_type, typename MapT::key_type>
reverse(const MapT& input)
{
std::multimap<typename MapT::mapped_type, typename MapT::key_type>
result;

for(typename MapT::const_iterator I = input.begin();
I != input.end(); ++I)
result.insert(std::make_pair(I->second, I->first));

return result;
}

// print any container
// where ostream operator<< is defined for container::value_type
template <typename ContainerT>
void
print(const ContainerT& input, const std::string& separator=" ")
{
std::copy(input.begin(), input.end(),
std::ostream_iterator<typename ContainerT::value_type>
(std::cout, separator.c_str()));
}

-- peter

Feb 1 '06 #10
Gavin Deane wrote:

If all you ever do with them is read and write individual elements
using operator[] then maybe iterators don't add much value. But that's
a small subset of what containers, iterators and algorithms can do for
you.


And that, in turn, is a small subset of what iterators and algorithms
can do for you. Containers are one way of getting sequences delimited by
iterators, but not the only way. Algorithms operate on sequences.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Feb 1 '06 #11
> I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?

For me (until now) iterators are very strangely objects because they are
useless for me.
But since most of members of containers use iterators, I am stumped.

I think, for using vector & map, index is far more useful than iterator.


Despite whatever others say, I have to agree. I stopped using iterators
several years ago and I am now living much happier live :)

Iterators are applicable just for continuous storage non-associative
containers (like vector), OTOH for many reasons this kind of containers
is the best performing in 99% of real world situations (especially if
you go a step further aboce STL and adopt wider range of continuous
containers, like circular buffers etc...). The remaining 1% can be
easily handled as special case (there are always special cases to
handle...).

Well, I have heard a lot about using iterators to handle non-container
entities like files, but so far I have not found real-world example
where that would have any real value above "wow" aspect often used to
advertise STL.

This leaves associative containers. The situation is more complicated
there, while "find" interface is quite easily expressed without the need
of using iterators, you quite often need a way how to iterate the
content of map. However, I have found that it is possible to implement
high-performing "dual access" associateve container with continuous
storage that behaves both as the map and as the array, so once again it
is possible to use indexes there - and in fact, this allows some pretty
interesting possibilities.

Mirek
Feb 1 '06 #12
In article <dr**********@volcano1.grnet.gr>,
Chameleon <ch******@hotmail.NOSPAM.com> wrote:
I am programming in C++ for 4 years, so I am not a newbie but I am not a
very experienced programmer on standard C++ libary.

My question is this:

Can you tell me one case which an iterator is better than index?


Iterators can point to sequences that don't exist except as a concept.
For example, you can make an iterator class that steps through prime
numbers without actually having to build a container of primes.

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 2 '06 #13
First, some containers such as list or set, do not have a concept of index.
Second, for these containers that can be indexed, iterating by index is
still "indirect". When you try to access container element using index, the
index is usually first translated to iterator and then dereferenced:

std::vector<int> v;
//...
v[i] = 3; // this actually emits code like *(v.begin() + i) = 3;

std::map<int ,int> m;
m[i] = 3; // this actually emits code like m.find(i)->second = 3;

The end result is that operations using indices are sometimes significantly
slower than operations with iterators. At least on MSVC 7.x, the difference
is quite noticeable.

cheers,
Marcin
Feb 2 '06 #14

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

Similar topics

9
2125
by: kosh | last post by:
I was wondering if there is or there could be some way to pass a generator an optional starting index so that if it supported that slicing could be made more efficient. Right now if you do use a...
10
3660
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
2
5488
by: Maciej Kwapulinski | last post by:
hallo. This is my question: let's assume a map like: map< string, my_object > str_map; map< string, my_object >::iterator iter = str_map.find("hallo"); map is an sorted container, so I...
29
3937
by: Hagen | last post by:
Hello, in a recent thread "speed of vector vs array" I read about the problem of the slow acces by addressing vector elements by indexing, unfortunately I see no workaround in my case. My...
6
3768
by: Joe | last post by:
I have a: vector<string> which contains a few dozen elements. I want to find the index of the element containing a certain string. for example: vector<string> strings;...
6
2225
by: routeslip | last post by:
I'm refering to an entry in an array by it's string key, as in foo. Is there a way to get the numeric index of that array without iterating through the entire array? What I need to do is find...
14
22525
by: micklee74 | last post by:
hi say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the...
4
7158
by: m_schellens | last post by:
How can I get from a vector index the iterator? typedef std::vector< doubleTdoubleV; doubleV xV; doubleV yV; // fill xV and yV with values (they have the same size) ....
2
9780
by: Christopher | last post by:
Seems odd, but I was wondering if I am in the middle of iterating through a vector, is there a way to calc which index I am currently on? something like: it - vec.begin()? I don't want to change...
0
7115
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...
0
7377
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...
1
7036
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...
1
5047
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3191
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1547
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
414
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...

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.