r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

6

u/just_ninjaneering Apr 05 '22

Iterators and it's types(CPP) And what is a namespace exactly?

1

u/ExtraFig6 Apr 06 '22

Iterators let you decouple your algorithms from your data structures. Instead of knowing specifically how your data is stored etc, you just need to know how to access it, how to traverse, and how fast you can do it (eg: is it random access? or do I have to go step by step)

For me, it helps to remember forward_iterator models singly linked lists, bidirectional_iterators model doubly linked lists, and random_access_iterators model arrays.

Let's compare forward_iterators and random_access_iterators. A forward iterator can do two things: you can dereference and you can ++ to go to the next element. This is enough to implement find_if:

template<std::forward_iterator I, class Pred>
I find_if(I begin, I end, Pred p) {
  while(begin!=end) {
    if(p(*begin)) break;
    ++begin;
  } 
  return begin;
}

But you can't implement quicksort because that needs random access.

For a random_access_iterator, you can do anything a forward_iterator can do. But you also get random access. You can add or subtract an offset and move that far through the data structure. Think of a pointer.