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;
}
}
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With