Is there a (convenient) way to extract the current iteration # inside a C ++ 11 "foreach" expression?

I am wondering if it is possible to somehow extract the current iteration number from a C ++ 11 foreach statement.

In this code:

for(auto &i: vect)
    if(i == 0) zero_value_index = /* here I want my index */;

I cannot find another way, but using old-fashioned fors int ito easily get my index.

Ideas?

+4
source share
3 answers

You could, I don't know, count the iterations :

int i = 0;
for (auto& el : container) {
    if (el == 0) zero_value_index = i;
    ++i;
}
+4
source

If you do not follow Ben-Voigt 's answer, the short answer is no.

As you have it vector, there is nothing wrong with the old-fashioned for-loop. Everything else will be unnecessarily complicated.

typedef std::vector <int>::size_type size_type ;
for(size_type i = 0; i < vect.size (); ++i) {
    // ...
}

, , :

template <class Container>
void DoStuff (Container &container)
{
    typedef Container::size_type size_type ;
    for (size_type i = 0; i < container.size (); ++i) {
        //...       
    }
}

- :

template <class Container>
struct StoreIndex
{
    typedef typename Container::size_type size_type ;
    typedef typename Container::value_type value_type ;

    StoreIndex (Container &container) : container (container), index (0)
    {
    }

    size_type index ;
    Container &container ;

    value_type operator () () {
        if (container [index] == 0) {
            return index++ ;
        }

        else {
            return container [index++] ;
        }
    }
};

:

std::generate (std::begin (v), std::end (v), StoreIndex <std::vector <int> > (v)) ;

, , (, std::map).

+2

I thought about it one night. The answer is yes. You can find the index excluding. This is due to the following two rules:

  • data in std :: vector is guaranteed to be continuous.
  • subtracting two pointers gives the distance in "object dimensions" rather than bytes.

.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> rhyme = { "humpty", "dumpty", "sat", "on", "a", "wall" };


int main()
{
    for(const auto& s : rhyme) {
        if (s == "on") {
            const size_t index = &s - rhyme.data(); // index computed here
            cout << "found at index " << index << endl;
        }    
    }

   return 0;
}
+1
source

Source: https://habr.com/ru/post/1539064/


All Articles