I am greatly stumped
How can I use an iterator in C# like a C++ iterator? I cannot find a Begin() or End() accessor, I cannot even find out how to declare an iterator. I have read about the Ienumerator. My goal is to implement the Merge Function. Here is part of my Merge function written in C++. Mostly, I am looking for the C# equivalent of what is shown, except I will be using a Reference type rather than integers.
void merge(vector<int>::iterator left, vector<int>::iterator right, vector<int>::iterator leftEnd, vector<int>::iterator rightEnd, vector<int>::iterator full)
{
while(left != leftEnd && right!= rightEnd) //compare left and right until the end of the vector is reached
{
if(*right < *left) //right < left so insert right to the output vector and advance the iterators
{
*full++ = *right++;
}
else //left < right so insert left to the output vector and advance the iterators
{
*full++ = *left++;
}
}
while(left != leftEnd) //copy any remaining elements into the output from left
{
*full++ = *left++;
}
}
Also, what collection(s) should I use? (currently I have been trying List<T> and LinkedList<T>).
It sounds like you want something like:
Here
fullwould need to be some sort ofIList<T>– .NET iterators don’t let you make changes to the underlying collection.You shouldn’t try to write “bridging” code to let you use .NET iterators like C++ ones; it’s much better to try to start thinking in terms of the .NET iterators when you’re using .NET.
Note that it’s quite rare to pass iterators around in .NET. It would be more natural to make your method to
IEnumerable<T>parameters, and do something like: