Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Or is it safe to use vector if the Enumerator of T is just listing all the elements?

question from:https://stackoverflow.com/questions/8764643/is-there-a-standard-c-equivalent-of-ienumerablet-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
505 views
Welcome To Ask or Share your Answers For Others

1 Answer

It isn't needed in C++, and here's why:

C# only supports dynamic polymorphism. So to create a reusable algorithm, you need an interface which all iterators will implement. That's IEnumerator<T>, and IEnumerable<T> is a factory for returning an iterator.

C++ templates, on the other hand, support duck typing. That means you don't need to constrain a generic type parameter by an interface in order to access members -- the compiler will look up members by name for each individual instantiation of the template.

C++ containers and iterators have implicit interfaces which is equivalent to .NET IEnumerable<T>, IEnumerator<T>, ICollection<T>, IList<T>, namely:

For containers:

  • iterator and const_iterator typedefs
  • begin() member function -- fills the need for IEnumerable<T>::GetEnumerator()
  • end() member function -- instead of IEnumerator<T>::MoveNext() return value

For forward iterators:

  • value_type typedef
  • operator++ -- instead of IEnumerator<T>::MoveNext()
  • operator* and operator-> -- instead of IEnumerator<T>::Current
  • reference return type from operator* -- instead of IList<T> indexer setter
  • operator== and operator!= -- no true equivalent in .NET, but with container's end() matches IEnumerator<T>::MoveNext() return value

For random access iterators:

  • operator+, operator-, operator[] -- instead of IList<T>

If you define these, then standard algorithms will work with your container and iterator. No interface is needed, no virtual functions are needed. Not using virtual functions makes C++ generic code faster than equivalent .NET code, sometimes much faster.


Note: when writing generic algorithms, it's best to use std::begin(container) and std::end(container) instead of the container member functions. That allows your algorithm to be used with raw arrays (which don't have member functions) in addition to the STL containers. Raw arrays and raw pointers satisfy all other requirements of containers and iterators, with this single exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...