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?

4
  • 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. Commented Nov 5, 2020 at 6: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 ? Commented Nov 5, 2020 at 6:58
  • 2
    This ranged for reference 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. Commented Nov 5, 2020 at 6: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. Commented Nov 5, 2020 at 7:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.