5 ms·
First sentence: “ An iterator is an object that points to an element inside a container” This is not the primary purpose of an iterator. Does anyone want to ha
by ribs 6y ago
First sentence: “ An iterator is an object that points to an element inside a container”
This is not the primary purpose of an iterator. Does anyone want to hazard a guess as to what an iterator’s primary purpose is? You? You? Bueller?
- millstone 6y agoI think you are arguing that iterators are "primarily" for iteration. But in C++ they really are like an abstraction over C pointers. For example, you can hold a std::list::iterator, and use it to efficiently delete from a linked list, without ever iterating. Sometimes C pointers are used for iteration, but I would not say that is their primary purpose.
- jhayward 6y ago> I think you are arguing that iterators are "primarily" for iteration I really wonder why people put up with something named this way then. "That fool thinks iterators are for iteration!" Clarity of abstraction and good naming are important, unless the practitioners are masochists.
- gpderetta 6y agoCursor would be a better name probably, but I wouldn't say the name is misleading, as iteration is an important use case.
- missblit 6y agoThe primary purpose of an iterator is to allow algorithms to be written in a generic manner without needing to know details about the type it's operating on. Since the algorithm only operates on the iterator type, any number of collections or other code that exposes that iterator type can be plugged into the same algorithm. Take `std::copy_n` for example. You _could_ use this to copy from one vector to another: std::vector<int> a = {1,2,3}, b = {0,0,0}; std::copy_n(a.begin(), a.size(), b.begin()); But iterators also allow the input and output collection types to be different: std::vector<int> a = {1,2,3}; std::array<int,3> b; std::copy_n(a.begin(), a.size(), b.begin()); Or even for the output to not be associated with a container at all. std::vector<int> a = {1,2,3}; std::copy_n(a.begin(), a.size(), std::ostream_iterator<int>(std::cout, " "));