4

The reverse algorithm in the C++ standard library is equivalent to

template <class BidirectionalIterator>
  void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
  while ((first!=last)&&(first!=--last)) {
    std::iter_swap (first,last);
    ++first;
  }
}

according to http://www.cplusplus.com/reference/algorithm/reverse/. I want to write the equivalent in C#:

public void Reverse<T> ( T first, T last ) 
{
    // ... 
}

First of all, how do you pass in two references to IEnumerators, with the second being one that can travel backwards? Is there a natural way of doing this or does it require first extending IEnumerable<T>?

Second of all, if the answer to the previous question is no, then is there a Skeet-certified C# way of writing reverse that equals the C++ one in terms of generality and effeciency? If so, what is it?

user6048670
  • 2,861
  • 4
  • 16
  • 20
  • Maybe this [thread](http://stackoverflow.com/questions/451099/implementing-a-bidirectional-enumerator-in-c-sharp) and @Brian Murphy-Booth answer is helpfull for you. To answer your question, C# has no bidirectional iterators – ckruczek Mar 16 '16 at 05:40
  • When you iterate in C++ you have a first and a last. In C# this concept doesn't exist. You iterate fully the collection... – xanatos Mar 16 '16 at 07:30
  • 1
    And there is a LINQ [`Enumerable.Reverse`](https://msdn.microsoft.com/en-us/library/bb358497.aspx) – xanatos Mar 16 '16 at 07:31

1 Answers1

0

The List<T> interface provides a Reverse() method which will do the same as C++ equivapent.

Have a look https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

schrieveslaach
  • 1,689
  • 1
  • 15
  • 32
  • I think you meant to link [this overload](https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx) instead. And this only answers the efficiency part of their question, not the generality part. – Joey Mar 16 '16 at 06:33