ITERATORS in C++

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys my name is ciano welcome back to my c plus plus series so today we're going to be talking all about iterators this is going to serve as more of an introductory video to iterators a lot of people have been asking me what are iterators should i be using iterators have they been somewhat replaced in the language this especially comes up a lot in universities who are still maybe not using the latest class plus standard in fact a lot of people message me and say help me my university is using c plus 03 which is a shame because it's 20 20 but we're not gonna get into the educational system in this video the point is what are iterators and do i really need to know how to use them so iterators are essentially a way for you to iterate over a collection of elements now the thing is an iterator is really up to the implementation in terms of how it's used meaning that i could write a class called apple and then add an iterator to it that might not make sense to you but i could use it in some kind of special way it's kind of like operator overloading you can make the plus plus operator do anything but for the most case if we look at the standard cpus library we can see that iterators are usually used for iterating over data structures so whether that be a simple array that you want to traverse or get through every element in that array maybe you have a vector you want to go backwards through every element maybe you have something a little bit more complicated like a set or a map or even a tree data structure i want to traverse that how do i do that well you need to use an iterator it's really easy to overlook iterators when you're just dealing with a simple data structure like a vector because we can simply use the index operator using the square brackets we can simply stick a value into there and retrieve that element at that given index but this doesn't always work for other data structures such as sets which don't really contain all of our elements in order so anyway long story short because i honestly think this does not need to be complicated at all iterators are used to iterate over a collection of elements and iterating over them is really simple as we'll see in a minute but first you know what isn't stuck in 2003 in terms of education skillshare for those of you who do not know what skillshare is skillshare is an online learning platform a community of people who come together to learn a new skill on the internet whatever it is that you're trying to learn whether that be illustration photography marketing business productivity literally almost anything skillshare has thousands of amazing classes for you to choose from and i love the fact that they're all really concise and simple and to the point even if you don't need to learn a new skill i mean i didn't think that i wanted to learn about illustration but to be honest it's been helping me relax so much which i feel is really needed these days something like productivity it it's not something that you necessarily always set out to learn but if you if you come across a class that teaches you to be more productive why not spend a few minutes going through that and you can do that with skillshare because of those concise classes coming in at just under 10 a month for an annual subscription it is an amazing offer but an even better offer is the fact that skillshare is offering the first 1000 people who click the link in the description below and sign up two free months of skillshare premium that's two whole months to check out the wide variety of courses that they have on that platform and decide for yourself if you want to stay and learn more or not huge thank you as always to skillshare for sponsoring this video let's dive in and take a look at what iterators are all about so as mentioned earlier iterators are used to iterate over a collection of data now you can really interpret this however you like it's possible to write custom iterators do a whole range of things but usually when we think of an iterator we think of having a collection of values such as this vector here and we want to traverse the entire collection part of the collection maybe we want to go backwards through the collection we essentially have the desire to get through at least some of the values inside this collection so how do we do that well let's look at some simple examples we have a vector here we have five values how do i print them all out to the console there are a number of ways we could of course do that the most common way which you'll probably think of is a for loop that simply iterates through values dot size like this so that we go through all of the five values that we have here and then we simply use the index operator here with the i variable to just retrieve the data at a particular index inside our array here so if i print this out into the console like this and i'll add in a little sc in get over here we should see one two three four five being printed out to the console as you can see that's what we get so we've essentially iterated through this entire collection and this is a pretty common way of doing that now let's also look at another way that we might do this because we don't really need this i variable is there a cleaner way that we can write this and of course there's something called a range based for loop since it's c plus 11. so what we can actually do is write the data type here which is end a name for the current element that we're iterating over and then finally the actual collection which in this case is values so in other words we're going through all the values here and then we now have this integer value to play with that's our current values i equivalent so we can just simply print that out to the console like this and well you can see that that results in some very very clean code this is usually my preferred way of iterating through collections if i don't need that i variable and there you can see we have the same result as before so how does this even work i mean it looks like seemingly magic code and it seems to work for this vector class so what exactly makes it work with the vector classes the vector class contains something specific that makes this range based for loop work and how does that work so the answer is yes it has something called an iterator now we're not really going to get into this too much there's a lot of different types of iterators here and we're actually going to even have a look at writing our own iterators for our custom data structure classes in the future but today we're just going to discuss how it actually works in practice and how you can use it basically a range based for loop works because the vector class provides a begin and end function which returns an iterator at a particular position so in other words this is really just some shorthand code for the more extended version which we're going to take a look at here so if we were to write this out you'll see that scd vector with that template specialization of end actually has another type inside it called iterator and there's a few different ones as you can probably see here there's iterator there's reverse iterator there's constitutor so just the regular iterator is what we can use to iterate through the values in a forward fashion and forward direction from beginning to end reverse iterator will do the opposite it will actually start at the end and go back to the beginning and then the const versions of these are the same but we can use it on a const vector because it's not going to actually let us affect the values it's not going to let us mutate the values just simply read them so if we just select the normal iterator that's what we have here how can we use this to iterate through all of the variables or all of the elements inside this std vector well you'd write a for loop just like you did here so we'd have an iterator we can call it i t that's a common name for it for iterator and we'll set this to the beginning of our collection which is going to be values.begin then we need to check the end condition so in other words just like with any other for loop at what condition does this for loop break at what condition does it terminate so it terminates if this iterator or rather at what condition does it not terminate right so this for loop will run as long as this statement is going to be true so as long as the iterator is not equal to the end of this collection so values.end will return an iterator that is actually already outside of the accepted range it's basically an invalid iterator so this is not really the end it's not the last element it's the element after the last element if that makes sense and then finally we need to write iterator plus plus you can also write it as plus plus iterator or as a postfix as well iterator plus plus it doesn't matter in this case now let me just slightly clean up this code and drop it down a bit so that you can see it all okay so that's it we're going through all of our values so now that we have an iterator though how do we get the value at that iterated position well you have to de-reference the iterator as if it was a pointer this works because they've just implemented this the reference operator kind of asterisk function inside the actual iterator class okay so now to print this out to the console we'll follow the same strategy as before we simply dereference the iterator and print it out like this and now what we should see is our one two three four five elements being printed for the third time and that is of course what we see over here great so why would you ever use iterators like this and to be honest the answer is you probably wouldn't these days because a range based for loop is essentially shorthand for this and of course it looks a lot cleaner however there are certain situations where you might want to manipulate the position of the iterator a good example is if you want to erase an element but still keep iterating over the rest of the collection in that case the iterator gets invalidated you have to deal with that or maybe you want to insert something into the middle based on a certain condition there's a few different scenarios in which you just simply can't use this because it just wouldn't work you need to be able to manipulate the position of the iterator and we'll probably get into those in a future video but obviously for something like a vector or an array with an index operator that simply takes in a numerical index it just ascends like it would for an array here they're not really necessary you don't actually have to write code like this because we can of course just write a normal for loop and use i as the index however iterators are essentially mandatory for other types that don't have such a simple indexing system because of course not everything is just a contiguous array with an index like we have here i mean think of something like a tree data structure how do we traverse through a tree we can't just increment an index what about an unordered set i mean that contains a bunch of unordered elements if i wanted to print all of them out to the console how would i do that the example i'm going to show you is specifically the unordered map here so an unordered map is essentially a hash map it obviously doesn't store its variables in any kind of order and we need to actually know the keys of the entries if we want to get the values out of there unless we iterate through them and that's what we're going to do here so let's create a little map here i'm going to just write an unordered map of scd string to maybe int we'll call this map so maybe this will like contain like some kind of name like cherno and maybe an associated score so we'll write channel five and maybe i don't know c plus 2 because obviously i'm cooler than c plus plus so with this map in mind if i wanted to iterate through it how would i do it well obviously i can't use a for loop like this because if i did that well my index would just be like 0 or 1 if i checked the map size and that's not what i need i need to actually iterate using the correct keys here so i'm forced to write some sort of iterator so let's write this out as a for loop that actually uses iterators so what i'll do is i'll take the entire type and you can see it's getting quite long and then maybe i don't want to like modify these values i just want to access them so i want to use a const iterator okay this is a huge type and because of that it's pretty common to use either a typedef or using along with the type so in other words maybe i could replace this part of it if i wanted to and just call it a score map and then that would obviously simplify things a lot so i can just do this now maybe i even want to define some kind of score map const iterator or something like that i could also do that by just assigning this to score map const iterator and now all i have to do is write code like this i honestly end up doing stuff like this a lot i don't i don't ever really use using with iterators like this but i do use it with the type sometimes so i'll leave it like that here and then just implement this as score map const iterator so iterating through this map i'll set the iterator equal to the beginning of the map of course like i did before i'll make sure that it iterates until we reach the end of the map and then i'll increment the iterator now this is a little bit different because this is a map i'm iterating through a map so how does that work i don't just have one element right like i would with like a set or a vector or an array or something like that i actually have two elements the key and the value so how do i access them well instead of just dereferencing it you can actually use the arrow operator and access two little elements here we have first and second first is going to be the key so i can just go ahead and assign that to key like that and then the second one is going to be my value and i'll just use the ampersand here to get this as a reference so that i'm not actually copying the value so i have iterator first and iterator second let's go ahead and print that out to the console we'll print the key followed by an equal sign and then value like this let's go ahead and run this and in fact what i might do is just take away the other code that we had here to keep our console nice and clean all right check this out so we have churno equals five and c plus plus equals two cool we're able to iterate through all of this now how can we maybe improve this code to make it a little bit better how can we use the same kind of range based for loops but with a map well let's check that out so i'm going to write for auto kv that's going to stand for key value in this case and then map yeah it's that simple so what this will do is actually retrieve this pair this iterator first and write a second if you actually look at what it is it's an scd pair so this is us now retrieving that std pair and now we can actually access the elements from within that so i still need this unfortunately but this obviously cleans up the code because i can just do kv dot first and kv dot second like that and then obviously if i print this out i should get the same result let me just add some end lines between this and here maybe let's see what we get all right as you can see we get the same result obviously but this again looks a lot cleaner now can we do better than that well yes we can as of cbs plus 17 we're able to use structured bindings what that means is that this code is going to look even cleaner we can actually retrieve this key in value right here inside this statement we can simply write auto key value with this kind of square brackets here and iterate through our map so if i drop this over here that's all we end up with and if i hit f5 there we go we're now iterating through this map three different ways and of course this code looks much much cleaner now keep in mind that you will have to make sure that your compiler supports people 17 and that you're actually compiling with that if we go into properties here as an example you can see that my c plus language standard under c c plus plus and language in visual studio is set to simple 17. if you're getting compiler errors which is quite common then make sure that you're actually compiling with c plus 17. okay so in summary the only way that we can iterate through a map or a set or something that is essentially unordered and doesn't have a simple kind of incrementing index system is by using an iterator and today we've discussed both using a normal iterator a const iterator range based for loops which actually use iterators as well as structured bindings with maps which is pretty cool and just to be super clear the reason these range based for loop shortcuts work is because we have an actual begin function inside our map or inside our well whatever collection or data structure we're using that actually returns an iterate in the first place if we didn't have that then that would in fact not work okay so hopefully that was a good introduction to iterators there is of course a lot more topics that we can actually cover in terms of iterators i would like to for one write our own iterators and we'll be adding them to the data structures that we've been going over the last few episodes of this series as well as i mentioned there's also some advanced things that you can try to do with iterators and i would encourage you to try that out as an exercise as homework if you will so for example try and remove an element from the center of a vector and see if you can adjust the iterator to deal with that and likewise maybe add an element into the middle of the vector and see if your iterator can deal with that those are great exercises and i might be revealing those solutions in the future but anyway i hope you guys enjoyed this video if you did as always please do not forget to hit that like button and subscribe if you are new to this channel we've got plenty more simple videos coming soon next time i think we'll have a go at actually writing our own iterators and adding them to our data structure classes but until then i hope you guys have a great day definitely don't forget to check out skillshare using the link in the description below and i will see you next time goodbye [Music] you
Info
Channel: The Cherno
Views: 94,781
Rating: undefined out of 5
Keywords: thecherno, thechernoproject, cherno, c++, programming, gamedev, game development, learn c++, c++ tutorial, iterators in c++, iterators, for loops, loops
Id: SgcHcbQ0RCQ
Channel Id: undefined
Length: 17min 8sec (1028 seconds)
Published: Fri Aug 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.