0
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

I found this as part of another question

How to navigate through a vector using iterators? (C++)

I would like to know how the following works ?

for (auto i : v) 

will navigate the entire vector, I need this information because I want to implement a custom vector class. In order to create custom vector class, do I need to create the begin(), end() functions and iterator member variable in it?

Evg
  • 25,259
  • 5
  • 41
  • 83
Vineesh Vijayan
  • 313
  • 1
  • 5
  • 13
  • 1
    You can also step through in a debugger and watch what it does, if you're interested. Concerning how to use it or how to implement this for your custom containers, please start with a tutorial. – Ulrich Eckhardt Nov 05 '20 at 06:58
  • I have clearly mentioned , I have to implement another Vector class , which has this feature , so if I want to implement , Do I need to implement the begin(),end() functions also ? – Vineesh Vijayan Nov 05 '20 at 06:58
  • 2
    [This ranged `for` reference](https://en.cppreference.com/w/cpp/language/range-for) have the equivalent "normal" `for` loops, if that's what you're wondering about. It will also tell you what is needed to support range-for in your classes. – Some programmer dude Nov 05 '20 at 06:59
  • Note that you don't necessarily need to define the iterator class "correctly" to make the ranged `for` loop works. For your iterator class, all you need is the `!=`(not equal), `++it`(prefix increment), and `*`(dereference) operators. – Ranoiaetep Nov 05 '20 at 07:39

0 Answers0