Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #37115

Re: auto i:v as iterator

From bartekltg <bartekltg@gmail.com>
Newsgroups comp.lang.c++
Subject Re: auto i:v as iterator
Date 2015-07-16 18:06 +0200
Organization ATMAN - ATM S.A.
Message-ID <mo8kql$cp2$1@node2.news.atman.pl> (permalink)
References <20150716103906.1f3f26b3@delligoertz.goertz.local>

Show all headers | View raw


On 16.07.2015 10:39, Ralf Goertz wrote:
> Hi,
>
> is it possible to have the new auto syntax for loops and get an iterator
> instead of a copy or a reference to the stored object itself? I would
> love to use the new syntax, but often I need to know what number in a
> vector the current object is. The following program doesn't compile.
>
> #include <vector>
> #include <iostream>
>
> int main() {
>      std::vector<int> v={47,11};
>      for (auto i:v) {
>          //std::cout<<i<<std::endl;
>          std::cout<<distance(i,v.begin())<<endl;
>      }
> 	return 0;
> }

#include <vector>
#include <iostream>

int main() {
     std::vector<int> v={47,11,11,15,154};
     for (auto & i:v) {
         //std::cout<<i<<std::endl;
         std::cout<<distance(v.begin() + 
(&(*v.begin())-&i),v.begin())<<endl;
     }
     return 0;
}


Results:
0
1
2
3
4


Do NOT use it. I.m almost certain it will blow up in your face;]
Just use normal for loop. The new syntax is there for your convenience,
you are not force to use it if it is harder to write something.
Even c-like loop with int/site_t  is _sometimes_ better.

bartekltg


Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

auto i:v as iterator Ralf Goertz <me@myprovider.invalid> - 2015-07-16 10:39 +0200
  Re: auto i:v as iterator Bo Persson <bop@gmb.dk> - 2015-07-16 11:09 +0200
    Re: auto i:v as iterator Ralf Goertz <me@myprovider.invalid> - 2015-07-16 12:00 +0200
      Re: auto i:v as iterator Öö Tiib <ootiib@hot.ee> - 2015-07-16 05:17 -0700
        Re: auto i:v as iterator Ralf Goertz <me@myprovider.invalid> - 2015-07-16 15:47 +0200
          Re: auto i:v as iterator Öö Tiib <ootiib@hot.ee> - 2015-07-16 08:27 -0700
            Re: auto i:v as iterator Ralf Goertz <me@myprovider.invalid> - 2015-07-17 07:57 +0200
  Re: auto i:v as iterator bartekltg <bartekltg@gmail.com> - 2015-07-16 18:06 +0200
  Re: auto i:v as iterator "Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com> - 2015-07-17 23:18 +0200

csiph-web