index vs iterator

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chameleon

    #1

    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.
  • Pete Becker

    #2
    Re: index vs iterator

    Chameleon wrote:[color=blue]
    > 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.[/color]

    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_iterato r<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)

    Comment

    • Ivan Vecerina

      #3
      Re: index vs iterator

      "Chameleon" <cham_gss@hotma il.NOSPAM.com> wrote in message
      news:drqitb$q7h $1@volcano1.grn et.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


      Comment

      • Gavin Deane

        #4
        Re: index vs iterator


        Chameleon wrote:[color=blue]
        > 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?[/color]

        The first case that springs easily to mind is that all the standard
        library algorithms use iterators.
        [color=blue]
        > 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.[/color]

        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

        Comment

        • roberts.noah@gmail.com

          #5
          Re: index vs iterator


          Chameleon wrote:[color=blue]
          > 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.[/color]

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

          Comment

          • Victor Bazarov

            #6
            Re: index vs iterator

            Chameleon wrote:[color=blue]
            > 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.[/color]

            What book are you reading to correct that? I recommend N. Josuttis, "The
            C+++ Standard Library".
            [color=blue]
            > My question is this:
            >
            > Can you tell me one case which an iterator is better than index?[/color]

            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.
            [color=blue]
            > For me (until now) iterators are very strangely objects because they are
            > useless for me.[/color]

            They exist to create _uniformity_ among all containers and ability to use
            all containers' iterators as well as regular pointers in all standard
            algorithms.
            [color=blue]
            > But since most of members of containers use iterators, I am stumped.[/color]

            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++...
            [color=blue]
            > I think, for using vector & map, index is far more useful than iterator.[/color]

            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

            Comment

            • Kai-Uwe Bux

              #7
              Re: index vs iterator

              Chameleon wrote:
              [color=blue]
              > 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.[/color]

              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

              Comment

              • Chameleon

                #8
                Re: index vs iterator

                Victor Bazarov wrote:[color=blue]
                > Chameleon wrote:[color=green]
                >> 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.[/color]
                >
                > What book are you reading to correct that? I recommend N. Josuttis, "The
                > C+++ Standard Library".[/color]

                I readed in the past "Thinking in C++" vol.1 and a big part of vol.2
                [color=blue][color=green]
                >> I think, for using vector & map, index is far more useful than iterator.[/color]
                >
                > 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'?[/color]


                yes

                Comment

                • Victor Bazarov

                  #9
                  Re: index vs iterator

                  Chameleon wrote:[color=blue]
                  > Victor Bazarov wrote:
                  >[color=green]
                  >> Chameleon wrote:
                  >>[color=darkred]
                  >>> 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.[/color]
                  >>
                  >>
                  >> What book are you reading to correct that? I recommend N. Josuttis, "The
                  >> C+++ Standard Library".[/color]
                  >
                  >
                  > I readed in the past "Thinking in C++" vol.1 and a big part of vol.2[/color]

                  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.
                  [color=blue][color=green][color=darkred]
                  >>> I think, for using vector & map, index is far more useful than iterator.[/color]
                  >>
                  >>
                  >> 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'?[/color]
                  >
                  >
                  >
                  > yes[/color]

                  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

                  Comment

                  • peter steiner

                    #10
                    Re: index vs iterator

                    Chameleon wrote:[color=blue]
                    > 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[/color]

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

                    - pointer like semantics (think of string::iterato r 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<t ypename MapT::mapped_ty pe, typename MapT::key_type>
                    reverse(const MapT& input)
                    {
                    std::multimap<t ypename MapT::mapped_ty pe, typename MapT::key_type>
                    result;

                    for(typename MapT::const_ite rator I = input.begin();
                    I != input.end(); ++I)
                    result.insert(s td::make_pair(I->second, I->first));

                    return result;
                    }

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

                    -- peter

                    Comment

                    • Pete Becker

                      #11
                      Re: index vs iterator

                      Gavin Deane wrote:
                      [color=blue]
                      >
                      > 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.
                      >[/color]

                      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)

                      Comment

                      • Mirek Fidler

                        #12
                        Re: index vs iterator

                        > I am programming in C++ for 4 years, so I am not a newbie but I am not a[color=blue]
                        > 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.[/color]

                        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

                        Comment

                        • Daniel T.

                          #13
                          Re: index vs iterator

                          In article <drqitb$q7h$1@v olcano1.grnet.g r>,
                          Chameleon <cham_gss@hotma il.NOSPAM.com> wrote:
                          [color=blue]
                          > 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?[/color]

                          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.

                          Comment

                          • Marcin Kalicinski

                            #14
                            Re: index vs iterator

                            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


                            Comment

                            Working...