C#指针,迭代器和泛型

Cod*_*lus 5 c# c++ generics collections iterator

我非常难过

如何在C#中使用迭代器,就像C++迭代器一样?我找不到Begin()或End()访问器,我甚至无法找到如何声明迭代器.我读过有关Ienumerator的文章.我的目标是实现合并功能.这是我用C++编写的Merge函数的一部分.大多数情况下,我正在寻找所显示内容的C#等价物,除了我将使用引用类型而不是整数.

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,我应该使用哪些系列?(目前我一直在努力List<T>LinkedList<T>).

Jon*_*eet 7

这听起来像你想要的东西:

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();    
}
Run Code Online (Sandbox Code Playgroud)

这里full需要某种IList<T>- .NET迭代器不允许您对底层集合进行更改.

不应该尝试编写"桥接"代码来让你使用像C++那样的.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
    }
}
Run Code Online (Sandbox Code Playgroud)