C # pointers, iterators and generics

I am very puzzled

How can I use an iterator in C # as a C ++ iterator? I cannot find Activate Begin () or End (), I cannot even learn how to declare an iterator. I read about Imenum. My goal is to implement the merge function. Here is the part of my Merge function written in C ++. Basically, I'm looking for the C # equivalent of what is shown, except that I will use the Reference type, not 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, which collection should I use? (I'm currently trying List<T>and LinkedList<T>).

+5
source share
4 answers

It looks like you want something like:

bool leftValid = left.MoveNext();
bool rightValid = right.MoveNext();

while (leftValid && rightValid)
{
    if (right.Current < left.Current)
    {
        full.Add(right.Current);
        rightValid = right.MoveNext();
    }
    else
    {
        full.Add(left.Current);
        leftValid = left.MoveNext();
    }
}

while (leftValid)
{
    full.Add(left.Current);
    leftValid = left.MoveNext();    
}

while (rightValid)
{
    full.Add(right.Current);
    rightValid = right.MoveNext();    
}

full IList<T> - .NET .

"", .NET, ++; .NET, .NET.

, .NET. IEnumerable<T> - :

using (IEnumerable<T> leftIterator = leftSequence.GetEnumerator())
{
    using (IEnumerable<T> rightIterator = rightSequence.GetEnumerator())
    {
        // Code as above, just using leftIterator and rightIterator
        // instead of left and right
    }
}
+7

.net ++. , ,

  • , IEnumerator<T>
  • ( , , ).
  • ,

, , foreach.


, IList<T>, , , . .

void Merge<T>(IList<T> container,int left, int right, int leftEnd, int rightEnd, int full)

container[left] *left.


, , ​​ ++.

+3

, GetEnumerator(), MoveNext() Current.

foreach , .

, "", .

IEnumerable<T> Merge<T>(IEnumerable<T> left, IEnumerable<T> right)
{
    ... yield return Min<T>(left.Current, right.Current); ..,
}
+2

List<T>, ArrayLists . (list[i]), list.Add(item);. . LinkedLists .

,

void merge(IEnumerator<int> left, IEnumerator<int> right, 
           List<int> full)
{
    // Jon Skeet code goes here
}

IEnumerable<int> intEnumerable = ...;
IEnumerator<int> intEnumerator = intEnumerable.GetEnumerator();

IEnumerable<T> . IEnumerable.

( @CodeInChaos).

0

All Articles