0

How do I iterate over vector in class e exacly this way below as shown in main

class Example{
public:
    vector <int> field;
    Example(){
        for(int i = 0;i< 10 ; i++)
            field.push_back(i);
    }
};

int main ()
{
    Example e();
    
    for (auto x : e){cout << x << endl;}        
    return 0;
}
273K
  • 29,503
  • 10
  • 41
  • 64
  • 3
    TL;DR - you need to provide `begin() const` and `end() const` methods for your class – Yksisarvinen Mar 06 '21 at 23:27
  • `Example e();` is broken anyway. It declares a function `e` accepting no arguments and returning an `Example`. That code stands no chance of compiling no matter what the subsequent for-loop looks like. That should read `Example e;` – WhozCraig Mar 06 '21 at 23:53
  • How do you implement these two functions begin() and end()? – NinjaSteve 1 Mar 07 '21 at 11:45
  • @Yksisarvinen Could you tell me how to implement these functions? – NinjaSteve 1 Mar 07 '21 at 15:20
  • 1
    The simplest way would be `auto begin() const {return field.begin();}` and same for `end()`, but we don't know if that's precesily what you need. Basically, you return vector iterators, but from your own class. – Yksisarvinen Mar 07 '21 at 16:53

0 Answers0