Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent to std::vector::iterators?

The following code snippet shows an iterator from the std::vector C++ lib. What is the C# equivalent to this? Can I simply loop through each item in the vector considering its not a linked list? What exactly is the iterator doing here and how can I do the equivalent in C#? The full code is here.

 std::vector<KMeanCluster>::iterator closest_cluster = clusters.begin();

    // Figure out which cluster this color is closest to in RGB space.
    for (std::vector<KMeanCluster>::iterator cluster = clusters.begin();
        cluster != clusters.end(); ++cluster) {
      uint distance_sqr = cluster->GetDistanceSqr(r, g, b);

      if (distance_sqr < distance_sqr_to_closest_cluster) {
        distance_sqr_to_closest_cluster = distance_sqr;
        closest_cluster = cluster;
      }
    }
like image 203
Robin Rodricks Avatar asked Nov 21 '25 17:11

Robin Rodricks


2 Answers

C++ standard library iterators are defined in a way to resemble pointers that walk through a collection. In C# every collection that implements IEnumerable can be iterated in a foreach loop. Apart from that you can still do something similar to C++ iterators in C# using Enumerators (which makes things harder in most cases):

IEnumerable<int> myCollection = new List<int> { 1, 2, 3 };
var enumerator = myCollection.GetEnumerator();
while(enumerator.MoveNext())
    Console.WriteLine(enumerator.Current);

Actually the above is how a foreach loop iterates through a collection under the hood.

foreach(int num in myCollection)
    Console.WriteLine(num);

So in terms of your code this is the exact (but hard to code and understand) equivalent:

IEnumerator<KMeanCluster> closest_cluster = clusters.GetEnumerator();
while (closest_cluster.MoveNext())
{
    uint distance_sqr = closest_cluster.Current.GetDistanceSqr(r, g, b);
    if (distance_sqr < distance_sqr_to_closest_cluster)
    {
        distance_sqr_to_closest_cluster = distance_sqr;
        closest_cluster = cluster;
    }
}

and this is the easiest equivalent:

foreach(KMeanCluster closest_cluster in clusters)
{
    uint distance_sqr = closest_cluster.GetDistanceSqr(r, g, b);
    if (distance_sqr < distance_sqr_to_closest_cluster)
    {
        distance_sqr_to_closest_cluster = distance_sqr;
        closest_cluster = cluster;
    }
}
like image 104
Sina Iravanian Avatar answered Nov 23 '25 06:11

Sina Iravanian


An iterator is basically an object that allows serial, non-random access to a container. Anyhow: You can use a normal loop in C#. A foreach loop is a bit closer to the C++ original syntaxwise

like image 35
rincewound Avatar answered Nov 23 '25 06:11

rincewound



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!